我有一个多次出现像这样的
键的字符串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)
替换为the a
,将@[b](b)
替换为the b
?即。
var str = '@[a](a) is a string with many @[a](a) but only one @[b](b)';
答案 0 :(得分:1)
您应该使用此代码:
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
构造函数时将其转义两次。
答案 1 :(得分:1)
示例[[a]]
匹配[]
或a]
,因为它会解析为
[[a] # Class, '[' or 'a'
] # followed by ']'
要修复它,请转义外括号文字,使它们成为文字。
output = output.replace(new RegExp('\\[[' + key + ']\\]', 'g'), obj[key]);
你甚至可以摆脱内部类括号,因为每次传递只有一个键。
output = output.replace(new RegExp('\\[' + key + '\\]', 'g'), obj[key]);