In this post I proved that the String.prototype.split function can behave differently in IE8 and below than it does in other browsers. For that reason, I wrote the following code that will fix the issue so that split should work the same in all browsers:

(function(split, toString, slice) {
  String.prototype.split = ','.split(/(()(,)())/, 5).join('|') == '|,||,|'
    ? split
    : function(delim, limit) {
      var me = this;
      if (toString.call(delim).slice(8, -1) == 'String') {
        return split.apply(me, arguments);
      }

      var end, start = 0, ret = [];
      me.replace(
        new RegExp(delim.source,
          'g' + (delim.ignoreCase ? 'i' : '') + (delim.multiline ? 'm' : '')),
        function(delim) {
          var arr = slice.call(arguments, 1, -1);
          end = arr.splice(-1)[0];
          ret.push.apply(ret, [me.slice(start, end)].concat(arr));
          start = end + delim.length;
          return delim;
        }
      );
      ret.push(me.slice(start));
      return limit > 0 ? ret.slice(0, limit) : ret;
    };
})(''.split, {}.toString, [].slice);

It is important to note that there is a way to improve the efficiency of this function if you plan on using it on big strings, but will also be setting the limit every time. On the other hand, most people probably don’t use the limit parameter of the split function so there is no reason to change the code in most cases.


Leave a Reply

Your email address will not be published. Required fields are marked *