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

6 Answers 6

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/

Sign up to request clarification or add additional context in comments.

4 Comments

This has to be the fastest method here.
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: 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: jsfiddle.net/Guffa/2Uc92/1
Thanks for you help. based on your input i have compiled the final version which also allows few special characters. check it out :)
4
for(var x = 0 ; x < array1.length; x++)
    string = string.replace(new RegExp(array1[x], "g"), array2[x])

FIDDLE

1 Comment

That will only replace the first occurance of each character.
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/

3 Comments

+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.
Thanks, this is great. Although Guffa already answered the question, this answer solves character combination issues.
Thanks for you help. Based on your and Guffa's answers i have compiled the final version which also allows few special characters. ;)
1

Assuming your two arrays have the same size:

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

4 Comments

That will only replace the first occurance of each character.
The replace method replaces all occurrences of the searched string: w3schools.com/jsref/jsref_replace.asp
Here is a jsFiddle 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.
mystr = mystr.split(array1[i]).join(array2[i]);// for replace all.
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

Comments

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.

2 Comments

Slow and the way you've done it limited to 4294967296 characters.:)
Using reduce like jsFiddle would have been better. Speed would still be (as) slow but no longer limited number of characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.