4

JS 中一次替换字符串中的多个内容的最简单方法是什么(没有它们干扰)?喜欢

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

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

4

2 回答 2

6
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"]);
于 2013-09-05T15:32:38.920 回答
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']);
于 2013-09-05T15:34:06.520 回答