Marco
Marco

Reputation: 2737

How to replace characters in a string with other characters?

I want to replace certain characters in a string with other characters. I´ve did my research and found that the best way is to use regular expressions... But, something doesn´t work ... Here´s what i did so far...

var alphabet = {
   'á':'a',
   'é':'e',
   'í':'i'
};

var word = $("input[name=phrase]").val();
alert(word);  //output: ok!

var url = word.replace(/áéí|/g, function(s) {
    return alphabet[s];
});

alert(url); //output: undefined,undefined,undefined...

Upvotes: 0

Views: 271

Answers (1)

user113716
user113716

Reputation: 322582

Match any of those characters using [], and capture the match(es) using () instead of looking for a match of those consecutive characters.

var url = word.replace(/[áéí]/g, function(s) {
    return alphabet[s];
});

DEMO: http://jsfiddle.net/5UmLV/1/


As noted by @Felix Kling the capture group was unnecessary. Updated to reflect that improvement.

Upvotes: 5

Related Questions