让 IE 用文字字符串“$0”替换正则表达式

发布于 2024-11-07 23:59:34 字数 362 浏览 0 评论 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

余厌 2024-11-14 23:59:34

写入 "$$0" 来转义 $ 符号。

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

開玄 2024-11-14 23:59:34

在 Chrome 和 Firefox 中,您可以通过使用函数作为替换函数的第二个参数来解决此限制:

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

我自己的测试表明,IE8 在这个问题上与其他浏览器是一致的。

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.

穿透光 2024-11-14 23:59:34

问题:

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

解决方案:

'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 "

说明: 我正在尝试查找“$”并替换为“$$”。要匹配“$”,您必须通过“\$”对其进行转义,要替换“$$$$”,您必须放置四个“$”作为“$$”的正则表达式转义“$”。乐趣!!

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!!

枯叶蝶 2024-11-14 23:59:34

@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 "\".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文