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

然而,这并不会产生“我有一只狗、一只山羊和一只猫”,而是产生“我有一只猫、一只猫和一只猫”。是否有可能在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".

当前回答

    var str = "I have a cat, a dog, and a goat.";

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

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

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

其他回答

以防有人想知道为什么原来海报上的解决方案不管用:

var str = "I have a cat, a dog, and a goat.";

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

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

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

使用我的replace-once包,您可以执行以下操作:

const replaceOnce = require('replace-once')

var str = 'I have a cat, a dog, and a goat.'
var find = ['cat', 'dog', 'goat']
var replace = ['dog', 'goat', 'cat']
replaceOnce(str, find, replace, 'gi')
//=> 'I have a dog, a goat, and a cat.'

所有的解决方案都很好,除了应用于闭包的编程语言(如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/

可以使用分隔符查找和替换字符串。

Var obj = { “firstname”:“约翰”, “姓”:“母鹿” } var文本= "你好{firstname},你的名字是{firstname}和姓氏是{lastname}" console.log (mutliStringReplace (obj、文本)) 函数mutliStringReplace(对象,字符串){ Var val =字符串 var entries = object .entries(object); entries.forEach ((para) = > { Var find = '{' + para[0] + '}' var regExp = new regExp (find,'g') val = val.replace(regExp, para[1]) }) 返回val; }