gpt4 book ai didi

javascript - js 正则表达式 "/(\s|\uFEFF|\xA0)+$/"让 firefox 和 chrome 忙不过来

转载 作者:行者123 更新时间:2023-11-29 16:09:53 30 4
gpt4 key购买 nike

当我尝试调用 CrossUI(一个 js 框架)的函数来 rtrim 由 jQuery grep 的 DOM 的文本内容时,firefox 和 chrome 将变得繁忙。我在源代码中发现这个正则表达式会阻止浏览器。我尝试了 /[\s\uFEFF\xA0]+$/ 并且它有效。为什么 /(\s|\uFEFF|\xA0)+$/ 卡住了?它们之间有什么内在差异?

$('body').text().replace(/(\s|\uFEFF|\xA0)+$/, "");
alert('pass');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div>
<div>&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</div>
<div>a</div>
</div>

最佳答案

根据 ECMA 5.1 specification , \s包括 WhiteSpaceLineTerminatorWhiteSpace 在其定义中包含 U+FEFF 和 U+00A0。

一个简单的测试

/^\s+$/.test("\ufeff\u00a0")

显示 IE9 和最新版本的 Firefox (38) 和 Chrome (43) 遵循这两个字符的规范。如果您决定放弃对旧浏览器的支持,则无需将这些字符手动添加到正则表达式中。只需使用 \s .

如果您需要在旧浏览器中支持它们,请将它们包含在一个字符类中:

[\s\ufeff\u00a0]

在符合 ECMA 5.1 的浏览器中使用交替将导致灾难性的回溯。由于交替创建了一个回溯1\s 的选择点匹配 ECMA 5.1 中的 U+00A0,\s\xA0\s|\uFEFF|\xA0提供 2 个有效选项以匹配一个不间断空格。当您有一串连续的空格(由 \s 定义)时,您将有 O(2n) 个案例要检查,其中 n 是上述子字符串中不间断空格的数量.这同样适用于 \ufeff ,但这种字符大量出现的情况比较少见。

相反,字符类不会为回溯创建选择点,因此在新旧浏览器中使用都是安全的。

1 从技术上讲,允许引擎将问题中的交替重写为字符类。但是,这在实践中并不常见,因为它会使引擎的实现变得复杂。

关于javascript - js 正则表达式 "/(\s|\uFEFF|\xA0)+$/"让 firefox 和 chrome 忙不过来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31533008/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com