6

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]

Community
  • 1
  • 1
chirag lathiya
  • 79
  • 2
  • 2
  • 11

5 Answers5

4

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

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • How would you handle if the word to be replaced has a dollar ($) sign. – ztalbot Jun 13 '19 at 18:35
  • @ztalbot Use `replaceArrayValue[i].replace(/\$/g, '$$$$')` – Wiktor Stribiżew Jun 13 '19 at 18:37
  • 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 Jun 13 '19 at 18:45
  • Solution found. My original string was different and all I had to do was a basic finalAns = finalAns.replace(replaceArray[i], replaceArrayValue[i]); – ztalbot Jun 13 '19 at 20:37
3

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

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • 1
    Should be the official answer, works like charm for me with replacing classes in string, all the other answers create problems – Wazime Aug 05 '19 at 21:28
1

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>
Sumit patel
  • 3,807
  • 9
  • 34
  • 61
0

I arrived to a solution using a declarative approach:

const string = 'boo and Boo2'
const dictionary = { boo: 'faa', boo2: 'faa2' }
return string.split(' ')
  .map(word => dictionary[word.toLowerCase()] ?? word)
  .join(' ')
// 'faa and faa2'
0

format method is for replacing all occurrences with order of the given array.

formatAll method is for replacing all first occurred words with order of the given array (which is asked for in the question)

String.prototype.format = function (_key, _data) {
  return this.split(_key).map(function (value, index) { return _data[index] ? value + _data[index] : (value ? value : '') }).join("");
}

String.prototype.formatAll = function (_keys, _data) {
  let shift = () => { _keys.shift(); return _data.shift() }
  return this.split(/\s+/).map(function (value) { return value == _keys[0] ? shift() : value }).join(" ")
}

"path/of/0/object/s/0/feature".format(0, [10,22])
//outputs
'path/of/10/object/s/22/feature'

"this is a string to replace. This string should be replaced using javascript".formatAll(["this","is","string","should","javascript"],["There","are","strings","have to","node.js"])
//outputs
'There are a strings to replace. This string have to be replaced using node.js'

"Merhaba dünya! Merhaba ay!".formatAll(["Merhaba"], ["Hello"])
//outputs
'Hello dünya! Merhaba ay!'

"Merhaba dünya! Merhaba ay!".formatAll(["Merhaba", "Merhaba"], ["Hello", "Selam"])
//outputs
'Hello dünya! Selam ay!'
aysum
  • 41
  • 1
  • 5