-1

I'd like to replace character (with variable) inside a string, here is my example:

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+']');

Why result is text tes_5 as name[5] end?

j08691
  • 197,815
  • 30
  • 248
  • 265
lolalola
  • 3,689
  • 19
  • 57
  • 92

2 Answers2

9

When using regex constructor, double escape:

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);
Toto
  • 86,179
  • 61
  • 85
  • 118
2

You need to escape the backslash, because backslash is an escape character for both string literals and regular expressions.

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);

In ES6 you can use a template literal with the String.raw tag. That prevents it from processing escape sequences inside the literal.

var oldId = 5;
var newId = 6; 
var content = 'text tes_5 as name[5] end';
content = content.replace(new RegExp(String.raw`name\[${oldId}\]`, 'g'), 'name['+newId+']');
console.log(content);
Barmar
  • 669,327
  • 51
  • 454
  • 560