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; } )
In JavaScript, backslashes are simply dropped from unrecognized escapes sequences.
\$is not a recognized escape sequence in a string literal, so this:means the same as this:
and in a
replacereplacement-string,$$means “a literal dollar sign”.What you want is this:
where the
$$becomes$and the$1becomes e.g.abc.(In other words: the way that you “escape” a dollar sign in a
replacereplacement string is by doubling it, not by prefixing it with a backslash.)