简体   繁体   中英

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

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.

You don't need a loop, just replace backwards:

var a = ['one', 'two', 'three'];
var b = ['two', 'three', 'four'];
var string = 'The only one and two and three';

string = string.replace(a[2], b[2]);
string = string.replace(a[1], b[1]);
string = string.replace(a[0], b[0]);

Note: this works for this example, it's not generic.

Just posting an alternate approach which splits the original string and replace it from dict object.

The dict object is built before the replace as it is essential to know what is being replaced.

var a = ['one', 'two', 'three'];
var b = ['two', 'three', 'four'];
var string = 'The only one and two and three';

var dict = {};
for (var i = 0; i < a.length; i++) {
    dict[a[i]] = b[i];
}

var stringtokens = string.split(' ');
for (var i = 0; i < stringtokens.length; i++) {
    if (dict.hasOwnProperty(stringtokens[i])){
        stringtokens[i] = dict[stringtokens[i]];
    }
}

console.log(stringtokens.join(' '));

Working fiddle

Do it backwards:

var a = ['one', 'two', 'three'];
var b = ['two', 'three', 'four'];
var string = 'The only one and two and three';

for (var i = string.length-1; i >= 0; i--) {
    string = string.replace(a[i], b[i]);
}

Working demo

You may reverse every array to achieve this. Another way is regular pattern.

Also, your code makes no sense. Why you iterating through string, if you need to iterate through arrays?

This would work:

for ( var i = 0; i < a.length; i++) {
    string = string.replace(a[a.length - 1 - i], b[b.length - 1 - i]);
}

Also, look at this universal way: http://phpjs.org/functions/str_replace/

You may do so:

str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars'); 

This function can get arrays as parameters.

Just do it the other way around. The problem is that after you replace one with two , you replace all two with three , and then you do the same thing with three and four , leaving you will all four at the end. If you reverse the order of your replaces, that won't happen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM