用变量替换括号之间的字符串

lol*_*ola -1 javascript regex replace

我想在字符串中替换字符(用变量),这是我的示例:

var oldId = 5;
var newId = 6; 
var content = 'text tes_5 as name[5] end';
content = content.replace(new RegExp('name\['+oldId+'\]', 'g'), 'name['+newId+']');
Run Code Online (Sandbox Code Playgroud)

为什么是结果text tes_5 as name[5] end

Tot*_*oto 9

使用正则表达式构造函数时,请使用两次转义:

var oldId = 5;
var newId = 6; 
var content = 'text tes_5 as name[5] end';
content = content.replace(new RegExp('name\\['+oldId+'\\]', 'g'), 'name['+newId+']');
console.log(content);
Run Code Online (Sandbox Code Playgroud)