gotofritz
gotofritz

Reputation: 3381

Inserting a $ in the replace string in a regular espression

Does anyone know why

"why?? <abc> and <a b c> and <a b>".replace( /<([^>]+)>/g, "\$$1" ); 

Returns

"why?? $1 and $1 and $1"

insted of

"why?? $abc and $a b c and $a b"

without the escaped $, the result is as expected

"why?? <abc> and <a b c> and <a b>".replace( /<([^>]+)>/g, "$1" )
//"why?? abc and a b c and a b"

I tried all sort of hacks, including for example

"why?? <abc> and <a b c> and <a b>".replace( /<([^>]+)>/g, String.fromCharCode( 36 ) + "$1" );

In the end I managed to get the output I wanted using a function as a replace string (see below) but I would like to know what I was doing wrong. Thanks in advance.

"why?? <abc> and <a b c> and <a b>".replace( /<([^>]+)>/g, function(m,m1,m2,p){return '$' + m1; } )

Upvotes: 2

Views: 119

Answers (1)

ruakh
ruakh

Reputation: 183331

In JavaScript, backslashes are simply dropped from unrecognized escapes sequences. \$ is not a recognized escape sequence in a string literal, so this:

"\$$1"

means the same as this:

"$$1"

and in a replace replacement-string, $$ means "a literal dollar sign".

What you want is this:

"$$$1"

where the $$ becomes $ and the $1 becomes e.g. abc.

(In other words: the way that you "escape" a dollar sign in a replace replacement string is by doubling it, not by prefixing it with a backslash.)

Upvotes: 7

Related Questions