I have two arrays.
var a = ['one', 'two', 'three'];
var b = ['two', 'three', 'four'];
var string = 'The only one and two and three';
I tried to use for-loop.
for ( var i = 0; i < string.length; i++) {
string = string.replace(a[0], b[0]);
string = string.replace(a[1], b[1]);
string = string.replace(a[2], b[2]);
}
But the problem is that after first iteration replaced value replaces again! I want to replace one with two, two with three and three with four.
Expected result: The only two and three and four
I get: The only four and four and four
One possible approach:
var dict = {};
a.forEach(function(el, i) {
dict[el] = b[i];
});
var patt = a.join('|');
var res = string.replace(new RegExp(patt, 'g'), function(word) {
return dict[word];
});
console.log(res); // The only two and three and four
Demo. It's really simple actually: first you create a dictionary (where keys are words to be replaced, and values are, well, words to replace them), second, you create an 'alternation' regex (with | symbol - you'll need to quote metacharacters if there are any). Finally, you go through the string with a single replace using this created pattern - and a replacement function, that looks for a particular 'correction word' in the dictionary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With