pinug pinug - 3 months ago 20
Javascript Question

insert a string at a specific position

i have an array and i want to insert "ZZ" if the current array value(string) contains "ata", the code should replace at the end of "ata" word.



var duplicatesArray = ["abıca","abrık","apşak","abbak","abu","aparma","apalisına","appak","aparmadutı","apşak","apışık","apşak","apışıklık","apışık","apalak","apılamak","apul","apul","apulamak","aparmak","at","arkasına","gelmek","ata","atabeg","at","eri","at","ağaç","at","oğlanı","at","akdarıcı","at","otayıcı","at","uşağı","at","oğlanı","at","oynağı","at","bırakmak","at","boynuna","düşmek","at","boynuna","düşmek","at","cıvlandurmak","at","çapmak","at","çapmak","at","depretmek","at","depmek","atı","doldurmak","at","segirtmek","ateş","evi","ateş","göyniigi","atışmak","ateşe","urmak","ateşe","nal","komak","at","şalmak","at","şalmak","at","tonı","at","kaşnısı","at","kaldırmak","at","kulağı","at","koparmals","at","koşmak","at","kulağı","götliği","atlaz","atlandurmak","atlandurmak","atlanmak","atlu","azuğı","atımı","yir","ata","atalar","atıcıduğı","aç","itmek","acıtğan","acıtmak","aç","dirilmek","acır","acırak","acışıklık","acışmak","aç","tutmak"
];

var uniqueArray = duplicatesArray.filter(function(elem, pos) {
return duplicatesArray.indexOf(elem) == pos;
});



for (var i = 0; i < uniqueArray.length; i++) {
var st = uniqueArray[i];
if((st.endsWith("mak")==false) && (st.endsWith("mek")== false) && (st.length>3))
{

var b = "ata";
var insert = "ZZ";

var position = st.indexOf("b");
st = st.slice(0, position) + insert + st.slice(position);


document.writeln(st);
document.write("<br>");


}


}




Answer

I may need to edit this answer later once some details have been clarified, but it seems like you should use the .map() method on your uniqueArray.

This code will walk through each word in the list and either let it unchanged or apply the replacement if all conditions are fulfilled.

// using a shorter, already deduplicated list for sake of clarity
var uniqueArray = [
  "abıca","gelmek","ata","atabeg","at","eri","yir","atalar","tutmak"
];

var result = uniqueArray.map(function(word) {
  return (
    !word.endsWith("mak") &&
    !word.endsWith("mek") &&
    word.length > 3 ?
    word.replace(/ata/, "ataZZ") : word
  );
});

console.log(result);

Comments