繁体   English   中英

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

[英]How to replace characters in string with values from array?

我有两个数组。

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

我试着用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]);
}

但问题是,在第一次迭代后,替换值再次替换! 我想更换one两个two three

预期结果: The only two and three and four

我得到: The only four and four and four

一种可能的方法:

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

演示 它实际上非常简单:首先你创建一个字典(其中键是要替换的单词,值是,以及替换它们的单词),其次,你创建一个'交替'正则表达式(带|符号 - 你需要引用元字符,如果有的话)。 最后,使用这个创建的模式进行单个replace的字符串 - 以及替换函数,该函数在字典中查找特定的“校正字”。

您不需要循环,只需向后替换:

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]);

注意:这适用于此示例,它不是通用的。

只是发布一个替代方法,它拆分原始字符串并将其替换为dict对象。

dict对象是在替换之前构建的,因为知道要替换的内容是必不可少的。

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(' '));

工作小提琴

向后做:

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]);
}

工作演示

您可以反转每个数组来实现此目的。 另一种方式是常规模式。

此外,您的代码没有任何意义。 如果需要迭代数组,为什么要遍历字符串?

这可行:

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

另外,看看这种通用的方式: http//phpjs.org/functions/str_replace/

你可以这样做:

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

此函数可以将数组作为参数。

只是反过来做。 问题是,你替换后onetwo ,更换所有的twothree ,然后你做同样的事情用threefour ,让你将所有four时结束。 如果你颠倒了替换的顺序,那就不会发生。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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