chirag lathiya chirag lathiya - 26 days ago 8
Javascript Question

javascript string replace with all occurence with array value

I want to replace all occurrences of a string but the issue is that I have an array of remove words & remove words value.

for example :

var string = "this is a string to replace. This string should be replaced using javascript";

var replaceArray = ["this","is","string","should","javascript"];

var replaceArrayValue = ["There","are","strings","have to","node.js"];

for (var i = replaceArray.length - 1; i >= 0; i--) {

var finalAns = string.replace(replaceArray[i],replaceArrayValue[i]);
}


I am expecting something like

There are strings to replace. There strings have to be replaced using node.js


I found some solutions in which I got the best solution here.
but I can't use the string in
/string/g
. I have to use
replaceArray[i]

Answer

If you prefer fixing your approach, you may use a RegExp constructor to build dynamic regexps with variables, and make sure you only match whole words enclosing the pattern with word boundaries. Do not forget to escape the literal patterns, and declare finalAns before the loop and initialize with the string var contents.

var string = "this is string to replace. this string should replace using javascript";
var replaceArray = ["this","is","string","should","javascript"];
var replaceArrayValue = ["There","are","strings","have to","node.js"];
var finalAns = string;
for (var i = replaceArray.length - 1; i >= 0; i--) {
    finalAns = finalAns.replace(RegExp("\\b" + replaceArray[i].replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "\\b", "g"), replaceArrayValue[i]);
}
console.log(finalAns);

Note that Roman's approach using a single static regex seems to be the most efficient for the current task (no need to build regexps dynamically each time).

Comments