Skip to content Skip to sidebar Skip to footer

Replace String With Values From Two Arrays

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 Arra

Solution 1:

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

FIDDLE

Solution 2:

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:

varstring = 'This is a text that needs to change';

var array1 = newArray('a', 'e', 'i', 'o', 'u');
var array2 = newArray('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/

Solution 3:

This sets up 1 RegExp and calls replace only once.

varstring = 'This is a text that needs to change';
var array1 = newArray('a', 'e', 'i', 'o', 'u');
var array2 = newArray('1', '2', '3', '4', '5');

var regex = new RegExp( '['+array1.join('')+']', 'g' );

var lookup = {}; // Setup a hash lookupfor( 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/

Solution 4:

Assuming your two arrays have the same size:

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

Solution 5:

Here's an example:

varstring = '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

Post a Comment for "Replace String With Values From Two Arrays"