0

This works:

var r="xS";
var regex = new RegExp(r); // Anchor at the end
var s="axS";
s = s.replace( regex, "Z" );
// Now, s is "aZ"

But this doesn't

var r="x$";
var regex = new RegExp(r); // Anchor at the end
var s="ax$";
s = s.replace( regex, "Z" );
// Now, s is STILL "ax$". NOT "aZ".

This doesn't work no matter where "$" is in the string r - e.g even if it's not at the end.

2
  • In the second bit of code, r is "x$$". Why would the the two $ symbols behave differently from each other? Commented Feb 15, 2012 at 16:26
  • @MichaelMyers - I removed the $ from the end of the regex. It was a red herring from exiting code (right-side anchor) but didn't affect the problem. Commented Feb 15, 2012 at 16:29

2 Answers 2

4

If you want to look for a $ in a string, you need to escape it. The $ is a special character in regexes meaning "end of string".

var r="x\$";
var regex = new RegExp( r + "$" ); // Anchor at the end
Sign up to request clarification or add additional context in comments.

3 Comments

Gotcha. For some reason I thought (errorneously) that RegExp would escape it automagically.
@DVK: It can't, how would it know what you're trying to do? And if it did, how would you use special characters? :-P
I said "for some reason", not for "for sane reason" :)
1

In the second case, "ax$" is a literal string which contains the character '$'. The regex (r) does not contain the literal character, but instead contains two anchors. You need to escape the '$' in the regex to match a literal value.

var r = "x\$"; should do the trick.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.