I'm replacing a bunch of values in a regex with dollar amounts. The problem is that in IE, if I attempt to replace with an amount of $0
(or, theoretically, $1
--$9
), the replace never occurs since the it's trying to replace a non-existant group:
'foo'.replace(/f/g, '$0');
I want the result of that replacement to be "$0oo", which it is in Chrome & FF, but not IE9 (haven't tried other versions of IE).
Chrome & FF have an "issue" with the following, in that I can't figure out how to replace with a literal $1
:
'foo'.replace(/(f)/g, '$1')
I'm replacing a bunch of values in a regex with dollar amounts. The problem is that in IE, if I attempt to replace with an amount of $0
(or, theoretically, $1
--$9
), the replace never occurs since the it's trying to replace a non-existant group:
'foo'.replace(/f/g, '$0');
I want the result of that replacement to be "$0oo", which it is in Chrome & FF, but not IE9 (haven't tried other versions of IE).
Chrome & FF have an "issue" with the following, in that I can't figure out how to replace with a literal $1
:
'foo'.replace(/(f)/g, '$1')
Share
Improve this question
edited May 17, 2011 at 0:06
SLaks
888k181 gold badges1.9k silver badges2k bronze badges
asked May 16, 2011 at 23:41
user578895user578895
4 Answers
Reset to default 8Write "$$0"
to escape the $
sign.
In Chrome and Firefox you can workaround this limitation by using a function as the second argument of the replace function:
'foo'.replace(/(f)/g, function(){return '$1';}); // => $1oo
My own testing shows that IE8 is consistent with the other browsers on this issue.
The Problem:
'My Bank balance is {0} '.replace(/\{0\}/,'$0.22')
results: "My Bank balance is {0}.22 "
This is not what we want
The solution:
'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 by '$$'. To match '$' you have to escape it by '\$' and to replace '$$$$' you have to put four '$' as RegEx escape '$' for '$$'. Fun!!
@SLaks that should be more like: write "$$" for literal "$".
@cwolves getting a literal instead of a 'special' character (like "$" here) usually involves either doubling it or prefixing it with "\".