最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript str_replace many at once - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 7

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

发布评论

评论列表(0)

  1. 暂无评论