Search code examples
javascriptstring

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

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

    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 less than 100, inserts the _n_th parenthesized submatch string, provided the first argument was a RegExp object.
    $<Name> Where Name is a capturing group name. If the group is not in the match, or not in the regular expression, or if a string was passed as the first argument to replace instead of a regular expression, this resolves to a literal (e.g., "$<Name>").