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,
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,
Share Improve this question edited Jul 6, 2012 at 16:25 user142162 asked Jul 6, 2012 at 16:21 Fran MarzoaFran Marzoa 4,5461 gold badge41 silver badges60 bronze badges 1- see this link may help you out – mgraph Commented Jul 6, 2012 at 16:24
3 Answers
Reset to default 7Use regex with the global flag:
var map = {
"á": "a",
"é": "e",
"í": "i",
"ó": "o",
"ú": "u"
};
"áéíóú".replace(/[áéíóú]/g, function(m){
return map[m];
});
Not really. Try this:
var map = {'á': 'a', 'é': 'e', 'í': 'i', 'ó': 'o', 'ú': 'u'};
var result = 'áéíóú'.replace(/./g, function(m) { return map[m] ? map[m] : m; });
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).