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

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

当前回答

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

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

其他回答

使用我的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.'
<!DOCTYPE html>
<html>
<body>



<p id="demo">Mr Blue 
has a           blue house and a blue car.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML;
    var res = str.replace(/\n| |car/gi, function myFunction(x){

if(x=='\n'){return x='<br>';}
if(x==' '){return x='&nbsp';}
if(x=='car'){return x='BMW'}
else{return x;}//must need



});

    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>

作为对以下问题的回答:

寻找最新的答案

如果在当前示例中使用“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);

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

为此,您可以使用https://www.npmjs.com/package/union-replacer。它基本上是一个字符串。Replace (regexp,…)对等体,它允许在一次传递中发生多次替换,同时保留string.replace(…)的全部功能。

披露:我是作者。开发这个库是为了支持更复杂的用户可配置替换,它解决了所有有问题的事情,比如捕获组、反向引用和回调函数替换。

上面的解决方案对于精确的字符串替换来说已经足够好了。