javascript - 替换字符串加上它周围的括号不适用于 RegExp

标签 javascript regex string replace

我有一个字符串,其中多次出现这样的键

var str = '[a] is a string with many [a] but only one [b]';

现在我有一个对象,其键的值在 str 中;

var obj = {a:'the a',b:'the b'};

我试过这样用它们的值替换这些键

let output = str;
for (const key in obj) {
      output = output.replace(new RegExp('[[' + key + ']]', 'g'), obj[key]);
    }

它的输出是

[the a is a string with many [the a but only one [the b

任何人都可以告诉我我错过了什么吗?

编辑

如何将 @[a](a) 替换为 a 并将 @[b](b) 替换为 b?即

 var str = '@[a](a) is a string with many @[a](a) but only one @[b](b)';

最佳答案

您应该使用此代码:

var str = '@[a](a) is a string with many @[a](a) but only one @[b](b)';
var obj = {a:'the a',b:'the b'};

let output = str;
for (const key in obj) {
   output = output.replace(new RegExp('@\\[' + key + '\\]\\(' + key + '\\)', 'g'), obj[key]);
}

console.log(output);
//=> "the a is a string with many the a but only one the b"

[ 必须在 Javascript 正则表达式中进行转义,并且在使用 RegExp 构造函数时将其转义两次。

关于javascript - 替换字符串加上它周围的括号不适用于 RegExp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46102847/

相关文章:

python - 正则表达式中的可选括号

python - 删除停用词/标点符号,标记并应用 Counter()

string - 在VBA中搜索字符串中包含小数的数字

javascript - 如何向状态 Hook 添加键?

Python 正则表达式列表使用列表

python - 如何告诉 Pandas read_csv 使用多个空格作为分隔符而不是单个空格?

c - 将带有 typedef 的结构数组传递给函数

JavaScript - 查找并替换数组中的单词

javascript - Angularjs :why controller can not access object properties from service? 我真的很困惑

javascript - 在页面加载时突出显示单选按钮