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]
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]
5 Answers
Reset to default 5If 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).
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."
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>
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'
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!'
var regex = new RegExp(replaceArray[i], 'g')
– Rajesh Commented Nov 7, 2016 at 9:04