我在我的浏览器中和一些在线 JavaScript 测试人员测试了这个代码片段:
var s = "testing \u0123 one two three";
s = s.replace(/\u[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]/g,'');
alert (s);
我希望警报中的结果只是“测试一二三”,但\u0123 所在的位置会出现一个有趣的字符。
我的问题是为什么替换不删除它?
我知道这不是最优雅的正则表达式。但这不是正确的吗?我正在删除反间隙字符,后跟 4 个十六进制字符。或者无论如何都在尝试。
最佳答案
My question is why doesn't the replace strip that out?
因为 /\u[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]/g
正则表达式字面匹配 \u
字符串,后跟 4 个十六进制字符。
而在字符串文字中指定的 \u0123
在解析步骤中被视为代码点,因此在运行时的字符串中没有 \u0123
,但2 个 UTF-16 物理字节。
您真正想要的是类似 [\u0080-\uFFFF
]:
> "testing \u0123 one two three".replace(/[\u0080-\uFFFF]/g, '')
"testing one two three"
该字符集指定所有不属于 ASCII 空间的代码点。
In string literals, regular expression literals, and identifiers, any character (code unit) may also be expressed as a Unicode escape sequence consisting of six characters, namely \u plus four hexadecimal digits.
引用文献:
关于javascript - 这个 JavaScript 代码片段似乎没有去除 JavaScript 中的 Unicode 转义字符 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29892338/