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); }
"\" 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+'\\$');
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.
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.
Double slash.