6

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...

asutherland
  • 2,849
  • 4
  • 32
  • 50
  • 1
    It's weird that you just happened to choose those characters. From your perspective it might seem like a bug. – ChaosPandion Sep 07 '12 at 03:14
  • I was replacing something with a very large block of text that happened to have those characters in it, it took me forever to narrow it down to those characters being the cause. – asutherland Sep 07 '12 at 03:19
  • 25% of my job is tracking down little mysteries like that. – ChaosPandion Sep 07 '12 at 03:21

2 Answers2

9

$& 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)

Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
  • Arg makes sense, This was part of a much bigger text string i was replacing and it took forever for me to figure out that those characters were the problem, thanks for the help! – asutherland Sep 07 '12 at 03:10
  • 1
    Better reference: http://ecma262-5.com/ELS5_HTML.htm#Section_15.5.4.11 , explains other variations of $ syntax. – Incognito Sep 07 '12 at 03:14
2

In your case:

var x = 'foo';
console.log(x.replace(x, function() {return '\\$&'}));

See the differences: http://jsfiddle.net/mPKEx/10/

You can specify a function as the second parameter. The above-mentioned special replacement patterns ($$, $&, $`, $', $n or $nn) do not apply in this case.

raciasolvo
  • 317
  • 7
  • 15