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 $$?

Answers:

Answer

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

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"
Answer

The replace method provides replacement patterns that start with a dollar sign. One of them is $$ which inserts a single $. A single dollar sign in the replacement string will result in a literal one.

So if you want clean literal dollar signs, use $$ replacement patterns accordingly:

console.log('aman/gupta'.replace('/','$$')); // aman$gupta
console.log('aman/gupta'.replace('/','$$$$')); // aman$$gupta
console.log('aman/gupta'.replace('/','$$$$$$')); // aman$$$gupta
Answer

Use below code its working for me.

var dollar = "$$$$";
console.log('abhishe/kadam'.replace('/', dollar.replace(new RegExp('\\$', 'g'), '$$$')));
Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.