"));​ Output: '\ foo'...">

Odd JavasScript string replaces behavior with $ &

With the following code:

var x = 'foo'; console.log(x.replace(x, "\\$&"));​ 

Output: '\ foo' as shown below: http://jsfiddle.net/mPKEx/

Why not?

 '\\$&"? 

I replace all x with "\ $ &" which is just an old plan table, so why does string.replace make some crazy replacement when the second argument of the function should not do anything but get the replacement in ...

+6
source share
2 answers

$ & is a special reference in Javascript string replacement. It points to a 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 )

+9
source

In your case:

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

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

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

+2
source

Source: https://habr.com/ru/post/924812/


All Articles