2

Is there any straightforward manner to make a character replacing in javascript of many chars in just one instruction with different replacement for each one, like it is possible in PHP?

I mean, something like:

replace('áéíóú', 'aeiou'); 

That replaces á with a, é with e, í with i, and so on...

Thanks a lot in advance,

1
  • see this link may help you out Commented Jul 6, 2012 at 16:24

3 Answers 3

7

Use regex with the global flag:

var map = { "á": "a", "é": "e", "í": "i", "ó": "o", "ú": "u" }; "áéíóú".replace(/[áéíóú]/g, function(m){ return map[m]; }); 
Sign up to request clarification or add additional context in comments.

Comments

3

Not really. Try this:

var map = {'á': 'a', 'é': 'e', 'í': 'i', 'ó': 'o', 'ú': 'u'}; var result = 'áéíóú'.replace(/./g, function(m) { return map[m] ? map[m] : m; }); 

Comments

3

Yes, you can do that in JavaScript:

var str = "áéíóú"; var result = str.replace(/[áéíóú]/g, function(m) { switch (m) { case "á": return "a"; case "é": return "e"; case "í": return "i"; case "ó": return "o"; case "ú": return "u"; } }); 

Another way is a lookup table:

var replacements = { "á": "a", "é": "e", "í": "i", "ó": "o", "ú": "u" }; var str = "áéíóú"; var result = str.replace(/[áéíóú]/g, function(m) { return replacements[m]; }); 

Those work because replace can accept a regular expression, and the "replacement" can be a function. The function receives the string that matched as an argument. If the function doesn't return anything, or returns undefined, the original is kept; if it returns something else, that's used instead. The regular expression /[áéíóú]/g is a "character" class meaning "any of these characters", and the g at the end means "global" (the entire string).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.