Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace characters in string with values from array?

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

like image 697
Vlad Holubiev Avatar asked May 10 '26 03:05

Vlad Holubiev


1 Answers

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.

like image 142
raina77ow Avatar answered May 12 '26 17:05

raina77ow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!