javascript string replace with all occurence with array value

10,840

Solution 1

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

Solution 2

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

Solution 3

without Regular Exp

Only can set variable string =finalAns; in loop . Because Every time Loop set old string then issue are occurs ,

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"];
alert(replaceArray.length);
for (var i = replaceArray.length - 1 ; i >= 0; i--) {

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

Snippet Exmaple

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"];

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

    var finalAns = string.replace(replaceArray[i],replaceArrayValue[i]);
    string =finalAns;
}
alert(finalAns);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Share:
10,840

Related videos on Youtube

chirag lathiya
Author by

chirag lathiya

Updated on June 04, 2022

Comments

  • chirag lathiya
    chirag lathiya almost 2 years

    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]

  • ztalbot
    ztalbot almost 5 years
    How would you handle if the word to be replaced has a dollar ($) sign.
  • Wiktor Stribiżew
    Wiktor Stribiżew almost 5 years
    @ztalbot Use replaceArrayValue[i].replace(/\$/g, '$$$$')
  • ztalbot
    ztalbot almost 5 years
    Wow your fast!. My original question could not be edited fast enough. 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"];
  • ztalbot
    ztalbot almost 5 years
    Solution found. My original string was different and all I had to do was a basic finalAns = finalAns.replace(replaceArray[i], replaceArrayValue[i]);
  • Wazime
    Wazime over 4 years
    Should be the official answer, works like charm for me with replacing classes in string, all the other answers create problems