1

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);
pewpewlasers
  • 3,025
  • 4
  • 31
  • 58
  • Take a look at http://stackoverflow.com/questions/2064047/javascript-replace-globally-with-array – Barbara Laird Jan 27 '14 at 23:49
  • You are searching for a [PHP `str_replace`](http://php.net/str_replace) JavaScript equivalent, something like http://phpjs.org/functions/str_replace/ : `output = str_replace( array1, array2, input )` – feeela Jan 27 '14 at 23:50
  • possible duplicate of [Replacing letters in a string using two arrays?](http://stackoverflow.com/questions/21064918/replacing-letters-in-a-string-using-two-arrays) – georg Jan 28 '14 at 01:28

6 Answers6

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

FIDDLE

BeNdErR
  • 17,471
  • 21
  • 72
  • 103
4

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/

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 2
    This has to be the fastest method here. – Xotic750 Jan 28 '14 at 00:37
  • Thanks this work great. One more question which I don't know if I should post as a separate question but here it goes: let's say your first array looks like this `('ae', 'a', 'e', ...)` and second like this `('!', '1', '2', ...)`. Is there a way to prioritize conversion of `'ae'` first before '`a`' and '`e`'? For example 'ae^&+-' must convert to '!^&+-' and not '12^&+-'. Any idea? – pewpewlasers Jan 28 '14 at 09:17
  • 1
    @pewpewlasers: If you have character combinations in the array, then you have to change the approach a bit. Create the pattern for the regular expression using `'(' + array1.join('|') + ')'`, and to find the matching string in the replace use a hash lookup like Matt showed. Demo: http://jsfiddle.net/Guffa/2Uc92/1/ – Guffa Jan 28 '14 at 09:31
  • Thanks for you help. based on your input i have compiled the final version which also allows few special characters. check it out :) – pewpewlasers Jan 28 '14 at 11:42
2

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/

Matt
  • 20,108
  • 1
  • 57
  • 70
  • +1 A lookup is a good idea. That is especially useful if you need to adjust the code for character combinations in the first array. – Guffa Jan 28 '14 at 09:35
  • Thanks, this is great. Although Guffa already answered the question, this answer solves character combination issues. – pewpewlasers Jan 28 '14 at 10:13
  • Thanks for you help. Based on your and Guffa's answers i have compiled the final version which also allows few special characters. ;) – pewpewlasers Jan 28 '14 at 11:43
1

Assuming your two arrays have the same size:

for(var i = 0; i < array1.length; i++){
    mystr = mystr.replace(array1[i], array2[i]);
}
Fedaykin
  • 4,482
  • 3
  • 22
  • 32
  • 1
    That will only replace the first occurance of each character. – Guffa Jan 28 '14 at 00:03
  • The replace method replaces all occurrences of the searched string: http://www.w3schools.com/jsref/jsref_replace.asp – Fedaykin Jan 28 '14 at 02:13
  • Here is a [jsFiddle](http://jsfiddle.net/Xotic750/c8wTN/) using your code, you can see clearly that it does not work as you are expecting and that the advice that @Guffa gave you is correct. – Xotic750 Jan 28 '14 at 03:23
  • mystr = mystr.split(array1[i]).join(array2[i]);// for replace all. – Ali Rasouli Jan 06 '22 at 18:55
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
elclanrs
  • 92,861
  • 21
  • 134
  • 171
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

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.

dev7
  • 6,259
  • 6
  • 32
  • 65
  • Slow and the way you've done it limited to 4294967296 characters.:) – Xotic750 Jan 28 '14 at 00:36
  • Using `reduce` like [jsFiddle](http://jsfiddle.net/Xotic750/Ca9ey/) would have been better. Speed would still be (as) slow but no longer limited number of characters. – Xotic750 Jan 28 '14 at 00:51