JavaScript replace() method dollar signs

I have a string like aman/gupta and I want to replace it to aman$$gupta and for that I am using JavaScript replace method as follows:

let a = "aman/gupta"
a = a.replace("/", "$")
console.log(a) // 'aman$gupta'

a = "aman/gupta"
a = a.replace("/", "$$")
console.log(a) // 'aman$gupta'

a = "aman/gupta"
a = a.replace("/", "$$$")
console.log(a) // 'aman$$gupta'

Why are the 1st and 2nd case identical and I get the expected result when I use $$$ instead of $$?


Solution 1:

It’s because $$ inserts a "$".

So, you need to use:

a = "aman/gupta";
a = a.replace("/", "$$$$"); // "aman$$gupta"

See the following special patterns:

Pattern   Inserts
$$        Inserts a "$".
$&        Inserts the matched substring.
$`        Inserts the portion of the string that precedes the matched substring.
$'        Inserts the portion of the string that follows the matched substring.
$n        Where n is a non-negative integer lesser than 100, inserts the nth
            parenthesized submatch string, provided the first argument was a
            RegExp object.

Solution 2:

Also you can use split and join for better performance and $ isn't special for those functions.

var a = "aman/gupta"
a = a.split('/').join('$$')
alert(a); // "aman$$gupta"

Solution 3:

To avoid the need to escape special characters you can use anonymous function as a replacer

a = "aman/gupta";
a = a.replace("/", function() {return "$$"});
console.log(a); // "aman$$gupta"

String.prototype.replace() documentation

Specifying a function as a parameter

You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. (Note: the above-mentioned special replacement patterns do not apply in this case.) Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.