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