用两个数组中的值替换字符串

时间:2022-04-10 08:51:14

I have a string for example:

我有一个字符串例如:

var string = 'This is a text that needs to change';

And then I have two arrays.

然后我有两个数组。

var array1 = new Array('a', 'e', 'i', 'o', 'u');
var array2 = new Array('1', '2', '3', '4', '5');

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:

现在,我要做的是用array1检查字符串并用数组2中的相应值替换字符串。所以使用函数来执行此操作我需要得到类似的内容:

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.

关于如何解决这个问题的任何想法?并且可能是一种有效的方法?因为我计划在巨大的数据块上使用它。

EDIT:

编辑:

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

6 个解决方案

#1


3  

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

Demo: http://jsfiddle.net/Guffa/2Uc92/

演示:http://jsfiddle.net/Guffa/2Uc92/

#2


4  

for(var x = 0 ; x < array1.length; x++)
    string = string.replace(new RegExp(array1[x], "g"), array2[x])

FIDDLE

小提琴

#3


2  

This sets up 1 RegExp and calls replace only once.

这将设置1个RegExp并仅调用一次替换。

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 regex = new RegExp( '['+array1.join('')+']', 'g' );

var lookup = {}; // Setup a hash lookup
for( var i=0 ; i<array1.length ; ++i )
    lookup[array1[i]] = array2[i];

string.replace(regex, function(c) { return lookup[c]; });
// "Th3s 3s 1 t2xt th1t n22ds t4 ch1ng2"

http://jsfiddle.net/2twr2/

http://jsfiddle.net/2twr2/

#4


1  

Here's an example:

这是一个例子:

var string = 'This is a text that needs to change';

var vowels = ['a','e','i','o','u'];
var numbers = [1,2,3,4,5];

var result = string.replace(/./g, function(char) {
  var idx = vowels.indexOf(char);
  return idx > -1 ? numbers[idx] : char;
});
//^ Th3s 3s 1 t2xt th1t n22ds t4 ch1ng2

#5


0  

Assuming your two arrays have the same size:

假设您的两个阵列具有相同的大小:

for(var i = 0; i < array1.length; i++){
    mystr = mystr.replace(array1[i], array2[i]);
}

#6


0  

For the purpose of exploring other interesting methods of doing the same thing, here is an implementation using array map.

为了探索做同样事情的其他有趣方法,这里是使用数组映射的实现。

It's just another cool way of doing it, without using a loop, replace or regexp.

这只是另一种很酷的方式,不使用循环,替换或正则表达式。

var string = 'This is a text that needs to change';
var array1 = ['a', 'e', 'i', 'o', 'u'];
var array2 = ['1', '2', '3', '4', '5'];

var a = string.split('');
a.map(function(c) {
    if (array1.indexOf(c) != -1) {
        a[ a.indexOf(c) ] = array2[ array1.indexOf(c) ];
    }
});

var newString = a.join('');
alert( newString );
//Outputs "Th3s 3s 1 t2xt th1t n22ds t4 ch1ng2"

Demo: JSFiddle

演示:JSFiddle

Interesting blog post about the array methods - map and reduce.

有趣的博客文章关于数组方法 - map和reduce。

I'd love to hear thoughts about performance of array map vs the other methods.

我很想听听阵列地图与其他方法相比的表现。

#1


3  

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

Demo: http://jsfiddle.net/Guffa/2Uc92/

演示:http://jsfiddle.net/Guffa/2Uc92/

#2


4  

for(var x = 0 ; x < array1.length; x++)
    string = string.replace(new RegExp(array1[x], "g"), array2[x])

FIDDLE

小提琴

#3


2  

This sets up 1 RegExp and calls replace only once.

这将设置1个RegExp并仅调用一次替换。

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 regex = new RegExp( '['+array1.join('')+']', 'g' );

var lookup = {}; // Setup a hash lookup
for( var i=0 ; i<array1.length ; ++i )
    lookup[array1[i]] = array2[i];

string.replace(regex, function(c) { return lookup[c]; });
// "Th3s 3s 1 t2xt th1t n22ds t4 ch1ng2"

http://jsfiddle.net/2twr2/

http://jsfiddle.net/2twr2/

#4


1  

Here's an example:

这是一个例子:

var string = 'This is a text that needs to change';

var vowels = ['a','e','i','o','u'];
var numbers = [1,2,3,4,5];

var result = string.replace(/./g, function(char) {
  var idx = vowels.indexOf(char);
  return idx > -1 ? numbers[idx] : char;
});
//^ Th3s 3s 1 t2xt th1t n22ds t4 ch1ng2

#5


0  

Assuming your two arrays have the same size:

假设您的两个阵列具有相同的大小:

for(var i = 0; i < array1.length; i++){
    mystr = mystr.replace(array1[i], array2[i]);
}

#6


0  

For the purpose of exploring other interesting methods of doing the same thing, here is an implementation using array map.

为了探索做同样事情的其他有趣方法,这里是使用数组映射的实现。

It's just another cool way of doing it, without using a loop, replace or regexp.

这只是另一种很酷的方式,不使用循环,替换或正则表达式。

var string = 'This is a text that needs to change';
var array1 = ['a', 'e', 'i', 'o', 'u'];
var array2 = ['1', '2', '3', '4', '5'];

var a = string.split('');
a.map(function(c) {
    if (array1.indexOf(c) != -1) {
        a[ a.indexOf(c) ] = array2[ array1.indexOf(c) ];
    }
});

var newString = a.join('');
alert( newString );
//Outputs "Th3s 3s 1 t2xt th1t n22ds t4 ch1ng2"

Demo: JSFiddle

演示:JSFiddle

Interesting blog post about the array methods - map and reduce.

有趣的博客文章关于数组方法 - map和reduce。

I'd love to hear thoughts about performance of array map vs the other methods.

我很想听听阵列地图与其他方法相比的表现。