我试图用多个其他单词替换字符串中的多个单词。字符串是“我有一只猫,一只狗和一只山羊。”

然而,这并不会产生“我有一只狗、一只山羊和一只猫”,而是产生“我有一只猫、一只猫和一只猫”。是否有可能在JavaScript中同时用多个其他字符串替换多个字符串,以便产生正确的结果?

var str = "I have a cat, a dog, and a goat.";
str = str.replace(/cat/gi, "dog");
str = str.replace(/dog/gi, "goat");
str = str.replace(/goat/gi, "cat");

//this produces "I have a cat, a cat, and a cat"
//but I wanted to produce the string "I have a dog, a goat, and a cat".

当前回答

const str = '感谢为Stack Overflow贡献一个答案!' Const substr = ['for', 'to'] 函数boldString(str, substr) { 让boldStr boldStr = str 字符串的子串。映射(e => { const strRegExp = new RegExp(e, 'g'); boldStr = boldStr。替换(strRegExp ' <强> $ {e} < / >强'); } ) 返回boldStr }

其他回答

这招对我很管用:

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

function replaceAll(str, map){
    for(key in map){
        str = str.replaceAll(key, map[key]);
    }
    return str;
}

//testing...
var str = "bat, ball, cat";
var map = {
    'bat' : 'foo',
    'ball' : 'boo',
    'cat' : 'bar'
};
var new = replaceAll(str, map);
//result: "foo, boo, bar"

我扩展了一下@本麦考密克斯。他的工作规则字符串,但不如果我转义字符或通配符。我是这么做的

str = "[curl] 6: blah blah 234433 blah blah";
mapObj = {'\\[curl] *': '', '\\d: *': ''};


function replaceAll (str, mapObj) {

    var arr = Object.keys(mapObj),
        re;

    $.each(arr, function (key, value) {
        re = new RegExp(value, "g");
        str = str.replace(re, function (matched) {
            return mapObj[value];
        });
    });

    return str;

}
replaceAll(str, mapObj)

返回"blah blah 234433 blah blah"

这样它将匹配mapObj中的键,而不是匹配的单词'

所有的解决方案都很好,除了应用于闭包的编程语言(如Coda, Excel,电子表格的REGEXREPLACE)。

我下面的两个原始解决方案只使用1个连接和1个正则表达式。

方法#1:查找替换值

其思想是,如果替换值不在字符串中,则附加替换值。然后,使用一个regex,我们执行所有需要的替换:

var str = "我有一只猫,一只狗,和一只山羊。"; STR = (STR +"||||猫,狗,山羊").replace( /猫(? = [\ s \ s] *(狗))|狗(? = [\ s \ s] *(山羊))|山羊(? = [\ s \ s] *(猫 ))|\|\|\|\|.* $ / gi, " $ 1 $ 2 $ 3”); document.body.innerHTML = str;

解释:

cat(?=[\s\S]*(dog)) means that we look for "cat". If it matches, then a forward lookup will capture "dog" as group 1, and "" otherwise. Same for "dog" that would capture "goat" as group 2, and "goat" that would capture "cat" as group 3. We replace with "$1$2$3" (the concatenation of all three groups), which will always be either "dog", "cat" or "goat" for one of the above cases If we manually appended replacements to the string like str+"||||cat,dog,goat", we remove them by also matching \|\|\|\|.*$, in which case the replacement "$1$2$3" will evaluate to "", the empty string.

方法#2:查找替换对

方法#1的一个问题是它一次不能超过9个替换,这是反向传播组的最大数量。 方法#2声明不只是附加替换值,而是直接替换:

var str = "我有一只猫,一只狗,和一只山羊。"; str = (str + " | | | |,猫= >狗,狗= >山羊,山羊= >猫”).replace ( / (\ b \ w + \ b) (? = [\ s \ s] * \ 1 =>([^,]*))|\|\|\|\|.* $ / gi, " $ 2 "); document.body.innerHTML = str;

解释:

(str+"||||,cat=>dog,dog=>goat,goat=>cat") is how we append a replacement map to the end of the string. (\b\w+\b) states to "capture any word", that could be replaced by "(cat|dog|goat) or anything else. (?=[\s\S]*...) is a forward lookup that will typically go to the end of the document until after the replacement map. ,\1=> means "you should find the matched word between a comma and a right arrow" ([^,]*) means "match anything after this arrow until the next comma or the end of the doc" |\|\|\|\|.*$ is how we remove the replacement map.

String.prototype.replaceSome = function() {
    var replaceWith = Array.prototype.pop.apply(arguments),
        i = 0,
        r = this,
        l = arguments.length;
    for (;i<l;i++) {
        r = r.replace(arguments[i],replaceWith);
    }
    return r;
}

/* 字符串的replaceSome方法 它需要尽可能多的参数,然后替换所有参数 我们指定的最后一个参数 2013年版权保存:Max Ahmed 这是一个例子:

var string = "[hello i want to 'replace x' with eat]";
var replaced = string.replaceSome("]","[","'replace x' with","");
document.write(string + "<br>" + replaced); // returns hello i want to eat (without brackets)

*/

jsFiddle: http://jsfiddle.net/CPj89/

我修改了本·麦考密克的答案以配合你的新测试用例。 我只是在正则表达式中添加了单词边界:

/\b(cathy|cat|catch)\b/gi

“运行代码片段”可以看到下面的结果:

var str = "我有一只猫,一个catch,和一个cathy."; var mapObj = { 凯茜:“猫”, 猫:“抓”, 抓住:“凯蒂” }; STR = STR .replace(/\b(cathy|cat|catch)\b/gi, function(matched){ 返回mapObj(匹配); }); console.log (str);