JavaScript多个同时替换

时间:2013-09-05 15:20:38

标签: javascript string replace

JS中最简单的方法是一次替换字符串中的多个东西(没有它们干扰)?像

"tar pit".replaceArray(['tar', 'pit'], ['capitol', 'house']);

...所以它产生“国会大厦”,而不是“cahouseol house”?

2 个答案:

答案 0 :(得分:5)

var replaceArray = function(str, from, to) {
   var obj = {}, regex;
   from.forEach(function(item, idx){obj[item] = to[idx];});

   regex = new RegExp('(' + from.join('|') + ')', 'g');
   return str.replace(regex, function(match){return obj[match]});
}

replaceArray("tar pit", ["tar", "pit"], ["capitol", "house"]);

答案 1 :(得分:2)

这个怎么样 -

function replaceArray(text, toBeReplacedArray, replacementArray) {
    for (var i = 0; i < toBeReplacedArray.length; i++) {
        var re = new RegExp(toBeReplacedArray[i], 'g');
        text = text.replace(re, '__' + i + '__');

    }

    for (var i = 0; i < replacementArray.length; i++) {
        var re = new RegExp('__' + i + '__', 'g');
        text = text.replace(re, replacementArray[i]);
    }
    return text;
}

replaceArray("tar pit", ['tar', 'pit'], ['capitol', 'house']);