Skip to content Skip to sidebar Skip to footer

Javascript Regex Object And The Dollar Symbol

In the code below. I expected true but i am getting false instead. What am I missing? var text = 'Sentence $confirmationlink$ fooo'; alert(placeHolderExists(text,'confirmation

Solution 1:

The "\" in the RegExp expression builder is treated as an escape character when building the string, just as it is in the actual RegExp. You need to escape twice, try:

newRegExp('\\$'+placeholdername+'\\$');

Solution 2:

Should be

functionplaceHolderExists(text,placeholdername) {  
  var pattern = newRegExp('\\$'+placeholdername+'\\$');    
  return pattern.test(text);
}

You need to double escape your $ signs

EDIT: annakata explains why.

Solution 3:

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

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

...is simpler, quicker, and doesn't fall over when you have funny characters in it.

Solution 4:

Double your slashes.

newRegExp('\\$'+placeholdername+'\\$');

Post a Comment for "Javascript Regex Object And The Dollar Symbol"