Javascript will replace the problem with $

I am trying to replace "this" in the example below with "$$ Ashok". I do not get the expected result.

var adHtmltext ="this is ashok" adHtmltext = adHtmltext.replace("this", "$$Ashok"); alert(adHtmltext ); 

why does it show one $ at the output? How to fix it?

Here is jsfiddle http://jsfiddle.net/RxDa5/

Please, help.

+4
source share
5 answers

See the MDN documentation :

The replacement string may include the following special replacement patterns:

$$ Inserts a "$".

So you need to do:

 adHtmltext.replace("this", "$$$$Ashok"); 

See also Javascript string replace weirdness - $$$$ crashes to $$ - what is the reason for this result? .

+6
source

$$ is the evacuation code for $ , since $ is the escape code for the regular expression backlink. Unfortunately, you need this:

 var adHtmltext ="this is ashok" adHtmltext = adHtmltext.replace("this", "$$$$Ashok"); alert(adHtmltext ); 
+3
source

The dollar sign is a reserved symbol for .replace()

In fact, in your jsFiddle code at the top right, you used it for a reserved purpose - i.e. $1 , which you have to capture part of the expression.

$$ used to exit the dollar sign. You need two dollar signs in this context for every dollar you really want.

This is because otherwise you could not have the string $1 .

+3
source

There are special patterns that can be included in the string that you are replacing with the target pattern, and the string with "$$" is one of them. See Mozilla MDN Docs for more information.

In your case, it is "$$" that becomes "$" as certain combinations of other characters with "$", for example, "$ &"; reserved for matching with specific substrings. If you want your replacement to work, just use "$$$$ Ashok", which will become "$$ Ashok" in the final line.

+2
source

The .replace method also takes regular expressions as the first argument, and if you group part of the text, you can include it in your output text using a "backlink", using the "$" symbol and a number indicating which group to use ($ 1 , $ 2, etc.).

Since the value "$" has a special meaning in this context, it needs to be escaped, and "$$" is an escape sequence to create a normal "$", so you just need the "$$$$ Ashok" in your code.

+2
source

All Articles