With the following code:
var x = 'foo';
console.log(x.replace(x, "\\$&"));
The output is ‘\foo’, as shown here: http://jsfiddle.net/mPKEx/
Why isn’t it
'\\$&"?
I am replacing all of x with “\$&” which is just a plan old string so why is string.replace doing some crazy substitution when the 2nd arg of the function isn’t supposed to do anything except get substitued in…
$& is a special reference in Javascript’s string replace. It points to the matched string.
$$ - Inserts a "$" $& - Refers to the entire text of the current pattern match. $` - Refers to the text to the left of the current pattern match. $' - Refers to the text to the right of the current pattern match. $n or $nn - Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.(Reference)