Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd JavasScript string replace behavior with $&

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

like image 392
asutherland Avatar asked Sep 07 '12 03:09

asutherland


People also ask

How do you replace a certain part of a string JavaScript?

replace() is an inbuilt method in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged. Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.

What can I use instead of replaceAll in JavaScript?

3.1 The difference between replaceAll() and replace() If search argument is a string, replaceAll() replaces all occurrences of search with replaceWith , while replace() only the first occurence. If search argument is a non-global regular expression, then replaceAll() throws a TypeError exception.

How do you replace all occurrences of a character in a string in JavaScript?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.

What is replace () in JavaScript?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.


2 Answers

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

like image 74
Anirudh Ramanathan Avatar answered Nov 03 '22 07:11

Anirudh Ramanathan


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.

like image 27
raciasolvo Avatar answered Nov 03 '22 09:11

raciasolvo