Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

like image 543
chirag lathiya Avatar asked Nov 07 '16 08:11

chirag lathiya


2 Answers

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).

like image 131
Wiktor Stribiżew Avatar answered Oct 24 '22 00:10

Wiktor Stribiżew


Use the following approach with replacement function:

var string = "this is string to replace. this string should replace using javascript",
    replaced = string.replace(/\b\w+\b/g, function ($m) {
        var search = ["this","is","string","should","javascript"],
            replacement = ["There","are","strings","have to","node.js"],
            key = search.indexOf($m);

        return (key !== -1)? replacement[key] : $m;
    });

console.log(replaced);

From "High Performance JavaScript" (by Nicholas Zakas):

"... regarding out-of-scope variables: store any frequently used out-of-scope variables in local variables, and then access the local variables directly."

like image 3
RomanPerekhrest Avatar answered Oct 24 '22 00:10

RomanPerekhrest