用两个数组中的值替换字符串 [英] Replace string with values from two arrays
问题描述
我有一个字符串例如:
var string = 'This is a text that needs to change';
然后我有两个数组。
var array1 = new Array('a', 'e', 'i', 'o', 'u');
var array2 = new Array('1', '2', '3', '4', '5');
现在,我要做的是用array1检查字符串并用数组中相应的值替换字符串2.所以有了这样做的功能,我需要得到类似的东西:
Now, what I what to do is check string with array1 and replace the string with corresponding value from array 2. So with a function to do this I need to get something like:
string = 'Th3s 3s 1 t2xt th1t n22ds to ch1ng2';
有关如何解决此问题的任何想法?并且可能是一种有效的方法?由于我打算在大量数据上使用它。
Any ideas on how to approach this problem? And may be an efficient approach? Since I plan to use this on huge chunks of data.
编辑:
根据这里的答案,我编写了一个代码,允许上述操作,同时也允许几个特殊字符。检查出来。
Based on the answers here I have compiled a code to allow the above operations while also allowing few special characters. Check it out.
var string = 'This is a text that needs to change';
var array1 = new Array('ee', 'a', 'e', 'i', 'o', ']');
var array2 = new Array('!', '1', '2', '3', '4', '5');
function escapeString(str){
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
var re = new RegExp('(' + escapeString(array1.join('ૐ')) + ')', 'g');
var nx = new RegExp(re.source.replace(/ૐ/g, "|"), 'g');
alert(nx);
var lookup = {};
for (var i = 0; i < array1.length; i++) {
lookup[array1[i]] = array2[i];
}
string = string.replace(nx, function(c){
return lookup[c]
});
alert(string);
推荐答案
如果要替换的字符只是普通字母,在正则表达式中没有任何特殊含义的东西,那么你可以创建一个只匹配那些字符的正则表达式。这允许您使用转换这些字符的函数使用单个替换:
If the characters to replace are just regular letters, and nothing that has a special meaning in a regular expression, then you can make a regular expression that matches only those characters. That allows you to use a single replace with a function that translates those characters:
var string = 'This is a text that needs to change';
var array1 = new Array('a', 'e', 'i', 'o', 'u');
var array2 = new Array('1', '2', '3', '4', '5');
var str1 = array1.join('');
var re = new RegExp('[' + str1 + ']', 'g');
string = string.replace(re, function(c){
return array2[str1.indexOf(c)]
});
演示: http://jsfiddle.net/Guffa/2Uc92/
这篇关于用两个数组中的值替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!