让 IE 用文字字符串“$0”替换正则表达式
我正在用美元金额替换正则表达式中的一堆值。问题是,在 IE 中,如果我尝试替换为一定数量的 $0
(或者理论上,$1
--$9
),替换永远不会发生,因为它试图替换一个不存在的组:
'foo'.replace(/f/g, '$0');
我希望替换的结果是“$0oo”,它在 Chrome & 中。 FF,但不是IE9(没有尝试过其他版本的IE)。
铬和FF 有以下“问题”,因为我不知道如何用文字 $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')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
写入
"$$0"
来转义$
符号。Write
"$$0"
to escape the$
sign.在 Chrome 和 Firefox 中,您可以通过使用函数作为替换函数的第二个参数来解决此限制:
我自己的测试表明,IE8 在这个问题上与其他浏览器是一致的。
In Chrome and Firefox you can workaround this limitation by using a function as the second argument of the replace function:
My own testing shows that IE8 is consistent with the other browsers on this issue.
问题:
解决方案:
说明: 我正在尝试查找“$”并替换为“$$”。要匹配“$”,您必须通过“\$”对其进行转义,要替换“$$$$”,您必须放置四个“$”作为“$$”的正则表达式转义“$”。乐趣!!
The Problem:
The solution:
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 应该更像是:为文字“$”写“$$”。
@cwolves 获取文字而不是“特殊”字符(如此处的“$”)通常涉及将其加倍或在其前面添加“\”前缀。
@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 "\".