admin管理员组文章数量:1244423
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 "\".
本文标签: javascriptGetting IE to replace a regex with the literal string quot0quotStack Overflow
版权声明:本文标题:javascript - Getting IE to replace a regex with the literal string "$0" - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740222458a2244077.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论