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).