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?
使用正则表达式构造函数时,请使用两次转义:
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)
| 归档时间: |
|
| 查看次数: |
56 次 |
| 最近记录: |