我有两个数组。
var a = ['one', 'two', 'three'];
var b = ['two', 'three', 'four'];
var string = 'The only one and two and three';
我尝试使用for循环。
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]);
}
但问题是,第一次迭代后替换值再次替换!我想将 one
替换为 two,将 two
替换为 三,将 三
替换为 < em>四个。
预期结果:唯一的两个和三个和四个
我得到:唯一的四个和四个和四个
最佳答案
一种可能的方法:
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 。实际上非常简单:首先创建一个字典(其中键是要替换的单词,值是要替换它们的单词),其次创建一个“替代”正则表达式(使用 |
符号 - 您需要引用元字符(如果有)。最后,您使用此创建的模式和一个替换函数通过一个replace
来遍历字符串,该函数在字典中查找特定的“更正词”。
关于javascript - 如何用数组中的值替换字符串中的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20477597/