问题描述
在工作中,我遇到了一个问题,即我们的应用程序的用户正在接收具有无效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?
推荐答案
那是因为 $ $替换字符串中的c $ c>具有特殊含义(组扩展)。看看这个例子:
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"));
另见。
这篇关于Javascript字符串取代怪异 - $$$$被折叠为$$ - 这个结果背后的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!