-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
  • 204,283
  • 31
  • 260
  • 272
lolalola
  • 3,773
  • 20
  • 60
  • 96

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
  • 89,455
  • 62
  • 89
  • 125
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
  • 741,623
  • 53
  • 500
  • 612