Javascript 字符串替换了奇怪的东西——$$$ 被折叠为 $$——这个结果背后的原因是什么? [英] Javascript string replace weirdness -- $$$$ gets collapsed to $$ -- what's the reason behind this result?

查看:19
本文介绍了Javascript 字符串替换了奇怪的东西——$$$ 被折叠为 $$——这个结果背后的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在工作中,我遇到了一个问题,即我们应用程序的用户收到的消息包含无效的 unicode 字符 (0xffff),根据标准,该字符永远不应映射到符号.

At work, I was encountering a problem where users of our application were receiving messages featuring an invalid unicode character (0xffff), which according to the standard, should never be mapped to a symbol.

为了快速工作,我做了以下工作:

As a quick work aound I did the following:

badStr.replace(/uffff/g, " ");

按预期工作,并让用户继续使用该应用程序,直到我们找到更好的解决方案.

Which works as expected, and lets the user continue using the application until we find a better solution.

然而,当我在玩这个的时候,我随机尝试了一个字符串替换$$$$",结果以某种方式折叠了$$".

However, while I was playing around with this, I randomly tried a string replacement of "$$$$" which somehow got collapsed "$$".

你可以自己看看.尝试在您的浏览器网址栏中粘贴以下几行:

You can see for yourself. Try pasting the following lines in your browser url bar:

javascript: alert(String.fromCharCode(0xffff).replace(/uffff/g, "@@@@"));

结果为@​​@@@

但是

javascript: alert(String.fromCharCode(0xffff).replace(/uffff/g, "$$$$"));

结果 $$

这实际上似乎是任何字符串替换的问题,以 $$$$ 作为字符串替换.

This actually seems to be a problem with any string replacement, with $$$$ as the string replacement.

两者:

javascript: alert(String.fromCharCode(0x1234).replace(/u1234/g, "$$$$"));
javascript: alert("hella".replace("h", "$$$$")); 

导致 $$ 崩溃.

关于为什么字符串替换会以这种方式进行的任何想法?

Any ideas as to why the string replacement behaves this way?

推荐答案

那是因为替换字符串中的 $ 具有特殊含义(组扩展).看看这个例子:

That's because $ in the replace string has special meaning (group expansion). Have a look at this example:

alert("foo".replace(/(.*)/, "a$1b"));

这就是为什么 $$ 被解释为 $ 的原因,对于您需要用 $1 实际替换某些内容的情况(字面上,没有组扩展):

That's why $$ is interpreted as $, for the case where you would need to actually replace something by $1 (literally, without group expansion):

alert("foo".replace(/(.*)/, "a$$1b"));

另见 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter.

这篇关于Javascript 字符串替换了奇怪的东西——$$$ 被折叠为 $$——这个结果背后的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆