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

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

当前回答

一种可能的解决方案是使用mapper表达式函数。

const regex = /(?:cat|dog|goat)/gmi;
const str = `I have a cat, a dog, and a goat.`;

let mapper = (key) => {
  switch (key) {
    case "cat":
      return "dog"
    case "dog":
      return "goat";
    case "goat":
      return "cat"
  }
}
let result = str.replace(regex, mapper);

console.log('Substitution result: ', result);
//Substitution result1:  I have a dog, a goat, and a cat.

其他回答

我们也可以使用split()和join()方法:

var str = "我有一只猫,一只狗,和一只山羊。"; str = str.split(“猫”)。映射(x =>{返回x.split("dog"))。地图(y = >{返回y.split(“山羊”). join(“猫”);}). join(“山羊”);}). join(“狗”); console.log (str);

使用正则函数定义要替换的模式,然后使用replace函数处理输入字符串,

var i = new RegExp('"{','g'),
    j = new RegExp('}"','g'),
    k = data.replace(i,'{').replace(j,'}');

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

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."

作为对以下问题的回答:

寻找最新的答案

如果在当前示例中使用“words”,则可以使用非捕获组扩展Ben McCormick的答案,并在左侧和右侧添加单词边界\b以防止部分匹配。

\b(?:cathy|cat|catch)\b

防止部分匹配的单词边界 (?:非捕获组 Cathy |cat|catch匹配其中一个选项 )关闭非捕获组 防止部分匹配的单词边界

原问题的例子:

let str = "我有一只猫,一只狗和一只山羊。"; const mapObj = { 猫:“狗”, 狗:“山羊”, 山羊:“猫” }; str = str.replace(/\b(?:猫|狗|山羊)\b/gi, matched => mapObj[matched]); console.log (str);

评论中的例子似乎并没有很好地工作:

let str = "I have a cat, a catch and a cathy."; const mapObj = { 凯茜:“猫”, 猫:“抓”, 抓住:“凯蒂” }; str = str.replace(/\b(?:cathy|cat|catch)\b/gi, matched => mapObj[matched]); console.log (str);

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

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中的键,而不是匹配的单词'