DVK
DVK

Reputation: 129383

Why doesn't a regex containing $ (built from a string) work?

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.

Upvotes: 0

Views: 56

Answers (2)

Jimmy
Jimmy

Reputation: 28386

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.

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227220

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

Upvotes: 4

Related Questions