Javascript Regex Object and Dollar Symbol

In the code below. I expected to be back, but instead I get a lie. What am I missing?

var text = "Sentence $confirmationlink$ fooo"; alert(placeHolderExists(text,'confirmationlink'); // alerts false function placeHolderExists(text,placeholdername) { var pattern = new RegExp('\$'+placeholdername+'\$'); return pattern.test(text); } 
+2
source share
4 answers

"\" in the RegExp expression builder is treated as an escape character when constructing a string, just like in a real RegExp. You need to escape twice, try:

 new RegExp('\\$'+placeholdername+'\\$'); 
+9
source

Must be

 function placeHolderExists(text,placeholdername) { var pattern = new RegExp('\\$'+placeholdername+'\\$'); return pattern.test(text); } 

You need to double access your $ signs

EDIT:
annakata explains why.

+3
source

This confusion is another example of why you shouldn't use regex if you really don't need to.

 return text.indexOf('$'+placeholdername+'$')!=-1; 

... simpler, faster and does not fall when it has funny characters.

+3
source

Double slash.

 new RegExp('\\$'+placeholdername+'\\$'); 
0
source

All Articles