Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 662
Aman Gupta Avatar asked Aug 10 '16 06:08

Aman Gupta


People also ask

What is $1 in replace JavaScript?

In your specific example, the $1 will be the group (^| ) which is "position of the start of string (zero-width), or a single space character". So by replacing the whole expression with that, you're basically removing the variable theClass and potentially a space after it.

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.

What is ${} called in JavaScript?

${} is a placeholder that is used in template literals. You can use any valid JavaScript expression such as variable, arithmetic operation, function call, and others inside ${}. The expression used inside ${} is executed at runtime, and its output is passed as a string to template literals.

What do dollar signs mean in JavaScript?

Updated on July 03, 2019. The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.


2 Answers

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>").
like image 101
Bhojendra Rauniyar Avatar answered Oct 07 '22 17:10

Bhojendra Rauniyar


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"
like image 21
Sojtin Avatar answered Oct 07 '22 17:10

Sojtin