Getting IE to replace regular expression with literal string "$ 0"

I am replacing a bunch of regular expression values ​​with a dollar amount. The problem is that in IE, if I try to replace with the number $0 (or, theoretically, $1 - $9 ), the replacement never occurs, because it tries to replace a non-existent group:

 'foo'.replace(/f/g, '$0'); 

I want the result of this replacement to be "$ 0oo", which is in Chrome and FF, but not IE9 (I have not tried other versions of IE).

Chrome and FF have a “problem” with the following: I cannot figure out how to replace the literal $1 :

 'foo'.replace(/(f)/g, '$1') 
+4
source share
4 answers

Type "$$0" to escape the $ sign.

+8
source

In Chrome and Firefox, you can get around this limitation by using the function as the second argument to the replace function:

 'foo'.replace(/(f)/g, function(){return '$1';}); // => $1oo 

My own testing shows that IE8 is compatible with other browsers on this issue.

+4
source

Problem:

 'My Bank balance is {0} '.replace(/\{0\}/,'$0.22') results: "My Bank balance is {0}.22 " This is not what we want 

Decision:

 'My Bank balance is {0} '.replace(/\{0\}/,'$$0.22') results: "My Bank balance is $0.22 " 'My Bank balance is {0} '.replace(/\{0\}/,"$0.22".replace(/\$/,'$$$$')) result: "My Bank balance is $0.22 " 

Explanation: I am trying to find "$" and replace it with "$$". To match "$", you need to escape from it "\ $", and instead of "$$$$" you need to put four "$" as the RegEx "$" escape code for "$$". Fun !!

+2
source

@SLaks, which should look more like this: write "$$" for the literal "$".

@cwolves, receiving a literal instead of a "special" character (for example, "$" here) usually includes either its double or the "\" prefix.

+1
source

All Articles