At times I use the
String#split function in order to create an array from a string based on a
RegExp delimiter. Unfortunately, today I realized that some browsers act differently than others. Let’s consider the following example:
var splitWithRegExpWorks = ','.split(/,/).length == 2;
In most browsers, the value of the above variable would be
true which is what you would probably expect. Unfortunately, I found that the value in IE8 is
In fact, all of the following in most browsers will alert
true, but in IE8 (and perhaps other strange browsers)
false is alerted:
alert(','.split(/,/).length == 2)
alert('a,'.split(/,/).length == 2)
alert(',b'.split(/,/).length == 2)
alert(',,'.split(/,/).length == 3)
alert('a,,c'.split(/,/).length == 3)
You can test any of the above snippets by simply click on the code block. FYI, you will not be able to run the code snippets as is in the console on this site because i’m using SyntaxHighlighter which seems to redefine the split function (thusly fixing the issue 😀 here).
String.prototype.split can return different results if using a regular expression as the delimiter.