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...
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.
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.
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.
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.
$& 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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With