I have a string for example:
var string = \'This is a text that needs to change\';
And then I have two arrays.
var array1 =
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
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
Interesting blog post about the array methods - map and reduce.
I'd love to hear thoughts about performance of array map vs the other methods.
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/
for(var x = 0 ; x < array1.length; x++)
string = string.replace(new RegExp(array1[x], "g"), array2[x])
FIDDLE
Assuming your two arrays have the same size:
for(var i = 0; i < array1.length; i++){
mystr = mystr.replace(array1[i], array2[i]);
}
This sets up 1 RegExp
and calls replace
only once.
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/