javascript - 如何用数组中的值替换字符串中的字符?

标签 javascript jquery arrays

我有两个数组。

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/

相关文章:

Python、Numpy : Cannot assign the values of a numpy array to a column of a matrix

javascript - 在此上下文中,您如何称呼 javascript 中的双管道?

javascript - Google Maps API 信息窗口都具有相同的内容

javascript - 销毁聚合物元素并重新创建具有其他属性的新元素……或者?

javascript - jquery参数化字符串就像rails中的参数化方法

java - 在java中按字母顺序排列二维数组

javascript - 渲染原始 HTML

javascript - 使用 Flot 0.7 的链接饼图返回 "undefined"链接

javascript - 将自定义导航栏转换为 Bootstrap 上的下拉菜单

python - 对 'N' 维 numpy 数组的操作