'1,2,3,4,5'.split(/(,)/) 结果:[-6ren">
gpt4 book ai didi

javascript - 通过捕获括号拆分正则表达式 - 浏览器支持 :

转载 作者:搜寻专家 更新时间:2023-11-01 04:08:56 24 4
gpt4 key购买 nike

查看此示例:

>'1,2,3,4,5'.split(/,/)

结果:["1", "2", "3", "4", "5"]

但是看看这个例子:

>'1,2,3,4,5'.split(/(,)/)

结果:["1", ",", "2", ",", "3", ",", "4", ",", "5"]

来自 MDN :

If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array. However, not all browsers support this capability.

问题:

我在哪里可以找到支持该功能的浏览器(和版本)列表。

mdn 不会公开该信息。

最佳答案

浏览器

互联网浏览器

来自Steven Levithan的博客和 XRegExp网站,已确认正确的行为(在结果数组中包含捕获组捕获的文本)实现到 Internet Explorer 8

我已经在 browserstack 上独立确认了这个结果,并进一步确认当提供带有捕获组的正则表达式时 String.split 的行为仅在 10 版的 Internet Explorer 中正确实现 之后。

下面是相关截图的链接:

附录

测试站点的完整源代码:

<html>
<head>
</head>
<body>
<script type="text/javascript">
document.write("<h1>Testing String.split, given regex with capturing group</h1>");

function runTest(num, actual, expected) {
var equals = true;

if (actual.length === expected.length) {
for (var i = 0; i < actual.length; i++) {
if (actual[i] !== expected[i]) {
equals = false;
break;
}
}
} else {
equals = false;
}

document.write("<h2>Test " + num + ":</h2>");
document.getElementsByTagName('body')[0].appendChild(document.createTextNode("'" + actual.join("'     '") + "'"));
document.write(equals ? "<h2>Compliant to ECMA 5.1</h2>" : "<h2>NOT compliant to ECMA 5.1</h2>");
}
</script>
<script type="text/javascript">
runTest(1, '1,2,3,4,5'.split(/(,)/), ["1", ",", "2", ",", "3", ",", "4", ",", "5"]);
</script>

<script type="text/javascript">
runTest(2, 'ABCDEF'.split(/()/), ["A", "", "B", "", "C", "", "D", "", "E", "", "F"]);
</script>

<script type="text/javascript">
runTest(3, 'text<a>text</a>'.split(/<(\/)?([^>]+)>/), ["text", void 0, "a", "text", "/", "a", ""]);
</script>
</body>
</html>

关于javascript - 通过捕获括号拆分正则表达式 - 浏览器支持 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24797170/

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