1

I want to replace {$variable_name} in a string,like "Hi, my name is {$name}." will be change to "Hi, my name is Sam."

I thought $ will be represented as \$, many RegExp test websites, like, https://www.regextester.com/, do the same.

My code is followed.

var str = "Hi, my name is {$name}.";
var reg = "\{\$name\}";
str = str.replace(new RegExp(reg,"g"), "Sam");
console.log(str); //Hi, my name is {$name}.

Then, I change the \$ to \\$, it worked.

var str = "Hi, my name is {$name}.";
var reg = "\{\\$name\}";
str = str.replace(new RegExp(reg,"g"), "Sam");
console.log(str); //Hi, my name is Sam.

But I don't understand why, maybe my poor search skills, I didn't find an explanation.

Can anyone explain this to me? Thank you very much.

J.Zou
  • 13
  • 2
  • 3
    Does this answer your question? [Why do regex constructors need to be double escaped?](https://stackoverflow.com/questions/17863066/why-do-regex-constructors-need-to-be-double-escaped) – ASDFGerte Mar 01 '20 at 04:28

1 Answers1

2

The reason for this is the way you are writing the regular expression. In a string, the \ character is used to escape, that is what is causing the behaviour you are seeing here. There is another way to write regular expressions which follows the same rules as these regex testing websites use. The difference is just wrapping the string in forward slashes instead of quotes.

var reg = /\{\$name\}/;

is the same as

var reg = "\{\\$name\}";
Genie
  • 315
  • 2
  • 12
  • 1
    Thank you. Now I got it. And autually "\{\\$name\}" can just be like "{\\$name}". Thank you for your help. – J.Zou Mar 01 '20 at 06:20