Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex split by capturing parentheses - browser support :

Looking at this sample :

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

Result : ["1", "2", "3", "4", "5"]

But looking at this sample :

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

Result : ["1", ",", "2", ",", "3", ",", "4", ",", "5"]

From 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.

Question :

Where can I find the list of browsers ( and versions) which supports that feature.

mdn doesn't expose that info.

like image 311
Royi Namir Avatar asked Jul 17 '14 07:07

Royi Namir


1 Answers

Browser

Internet Explorer

From the blog of Steven Levithan and XRegExp website, it is confirmed that the correct behavior (inclusion of text captured by capturing groups in the result array) is not implemented up to Internet Explorer 8.

I have independently confirmed this result on browserstack, and further confirmed that the behavior of String.split when a regex with capturing group is supplied is correctly implemented for Internet Explorer only from version 10 onwards.

Below are links to relevant screenshots:

  • Screenshot of Windows 7 IE 8.0
  • Screenshot of Windows 7 IE 9.0
  • Screenshot of Windows 7 IE 10.0
  • Screenshot of Windows 7 IE 11.0

Appendix

Full source code of the test site:

<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>
like image 77
nhahtdh Avatar answered Sep 25 '22 04:09

nhahtdh