-2

I have this code

var str = "Some text :$0";
var i = 0;

alert(str.replace(new RegExp("\:\$" + i, "g"), 'here'));

see here.

Why is it not working? If I do it like this /\:\$:0/g instead of using the RegExp object then it works but I can't use a variable in the pattern that way. Whats wrong?

php_nub_qq
  • 15,199
  • 21
  • 74
  • 144

1 Answers1

8

Because in string literals, \ has a special meaning. If you want to actually put a \ in the regular expression, you need to escape it in the string literal:

new RegExp("\\:\\$" + i, "g")

But : has no special meaning in regular expressions, no need to escape it:

new RegExp(":\\$" + i, "g")

var str = "Some text :$0";
var i = 0;

console.log(str.replace(new RegExp(":\\$" + i, "g"), 'here'));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875