我有一个字符串,多次出现这样的键
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)';
您应该使用以下代码:
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
构造函数时应转义两次。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句