我有一个字符串,其中多次出现这样的键
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/