0

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...
2
  • 2
    Is the pipe a typo or really part of your code? Commented Sep 21, 2011 at 23:53
  • Thought so, just making sure. :) Commented Sep 22, 2011 at 4:56

1 Answer 1

5

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.

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

5 Comments

Is a capture group really necessary? Anyways, +1.
No, not necessary. word.replace(/[áéí]/g, function(s) {return alphabet[s];}) works fine.
thanks... that idea works. What if there is more then 1 character to be replace. like '...' : '' how does it go in the regular expressions? i tried using quotes, like '...' but then it confuses the actual quote with a replacement character '\'' : ''
@Marco: Then get rid of the [] , and use | to separate the possibilities: /á|é|í|\.\.\./g jsfiddle.net/5UmLV/4
@Marco: Are you sure these are three dots? Maybe you have an ellipsis, which is one character. Just saying that not everything that looks like multiple characters consists of multiple 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.