我试图用多个其他单词替换字符串中的多个单词。字符串是“我有一只猫,一只狗和一只山羊。”
然而,这并不会产生“我有一只狗、一只山羊和一只猫”,而是产生“我有一只猫、一只猫和一只猫”。是否有可能在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".
在这个实例中,这可能不能满足您的确切需求,但我发现这是一种有用的方法,可以替换字符串中的多个参数,作为通用解决方案。它将替换参数的所有实例,无论它们被引用了多少次:
String.prototype.fmt = function (hash) {
var string = this, key; for (key in hash) string = string.replace(new RegExp('\\{' + key + '\\}', 'gm'), hash[key]); return string
}
你可以这样调用它:
var person = '{title} {first} {last}'.fmt({ title: 'Agent', first: 'Jack', last: 'Bauer' });
// person = 'Agent Jack Bauer'
以防有人想知道为什么原来海报上的解决方案不管用:
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."
通过使用原型函数,我们可以通过传递对象的键和值以及可替换的文本轻松地进行替换
String.prototype.replaceAll =函数(obj keydata =“关键”){
const键= keydata.split(关键);
返回Object.entries (obj) .reduce((,(关键,val)) = > a.replace(“${键[0]}${关键}${键[1]}',val),)
}
Const data=' hidden dv SDC sd ${yathin} ${ok}'
console.log (data.replaceAll ({yathin: 12,好的:“嗨”},“${关键}”))
作为对以下问题的回答:
寻找最新的答案
如果在当前示例中使用“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);
使用我的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.'