使用多个字符串替换其他多个字符串

28 浏览
0 Comments

使用多个字符串替换其他多个字符串

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

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

admin 更改状态以发布 2023年5月24日
0
0 Comments

作为回答:

寻找最新答案

如果你像你目前的例子一样使用"words",你可以扩展Ben McCormick的答案,使用一个非捕获组并在左右两侧添加单词边界\b以防止部分匹配。

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

  • \b 一个单词边界,以防止部分匹配
  • (?: 非捕获组
    • cathy|cat|catch 匹配其中一个替代项
  • ) 关闭非捕获组
  • \b 一个单词边界,以防止部分匹配

原问题的示例:

let str = "I have a cat, a dog, and a goat.";
const mapObj = {
  cat: "dog",
  dog: "goat",
  goat: "cat"
};
str = str.replace(/\b(?:cat|dog|goat)\b/gi, matched => mapObj[matched]);
console.log(str);

评论中给出的示例似乎效果不佳:

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

0
0 Comments

具体解决方案

你可以使用一个函数来替换每个需要替换的部分。

var str = "I have a cat, a dog, and a goat.";
var mapObj = {
   cat:"dog",
   dog:"goat",
   goat:"cat"
};
str = str.replace(/cat|dog|goat/gi, function(matched){
  return mapObj[matched];
});

jsfiddle示例

泛化解决方案

如果你想动态地维护正则表达式,并将将来的替换添加到映射中,你可以这样做

new RegExp(Object.keys(mapObj).join("|"),"gi"); 

以生成正则表达式。因此,它将如下所示

var mapObj = {cat:"dog",dog:"goat",goat:"cat"};
var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
str = str.replace(re, function(matched){
  return mapObj[matched];
});

要添加或更改任何其他替换,只需编辑映射即可。

使用动态正则表达式的fiddle

使其可重用

如果您想将此作为通用模式,则可以将其提取到函数中,如下所示

function replaceAll(str,mapObj){
    var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
    return str.replace(re, function(matched){
        return mapObj[matched.toLowerCase()];
    });
}

然后,您可以将字符串和您要替换的映射传递给函数,并且它将返回转换后的字符串。

使用函数的fiddle

为了确保Object.keys在旧版浏览器中起作用,请添加polyfill,例如从MDNEs5

0