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,

Fran Marzoa
  • 4,293
  • 1
  • 37
  • 53

3 Answers3

7

Use regex with the global flag:

var map = {
    "á": "a",
    "é": "e",
    "í": "i",
    "ó": "o",
    "ú": "u"
};

"áéíóú".replace(/[áéíóú]/g, function(m){
    return map[m];
});
Esailija
  • 138,174
  • 23
  • 272
  • 326
3

Not really. Try this:

var map = {'á': 'a', 'é': 'e', 'í': 'i', 'ó': 'o', 'ú': 'u'};
var result = 'áéíóú'.replace(/./g, function(m) { return map[m] ? map[m] : m; });
Mitya
  • 33,629
  • 9
  • 60
  • 107
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).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875