9

I am trying to use this function to create 2 results from value

function split(val){
  return val.split( /,\s*/ );
};
value = "Jim, ";
var terms = split( value );

terms;

All other browsers including IE9, will produce terms = ["Jim", ""]

However, IE8 and probably IE7 produces this : terms = ["Jim"]

Does anyone have any suggestions or alternatives that could possibly work for IE8 ?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Trip
  • 26,756
  • 46
  • 158
  • 277
  • 1
    Interesting find. IE8 behaves properly when splitting with a string (such as `", "` in this example), but doesn't have that empty string at the end when splitting on a regex... strange. – Niet the Dark Absol Jun 21 '12 at 18:40
  • 2
    For an alternative, see the answer on [http://stackoverflow.com/questions/1453521/javascript-split-doesnt-work-in-ie][1] [1]: http://stackoverflow.com/questions/1453521/javascript-split-doesnt-work-in-ie – Andrew Morton Jun 21 '12 at 18:58
  • Can you explain in which case you'll worry about empty last element on array? Take a look at my edit – abuduba Jun 21 '12 at 19:32

2 Answers2

5

You might be better off going with:

val.split(',')

This seems to work consistently in all browsers.

Any trailing whitespace after the commas still has to be stripped off afterwards. Something along the lines of:

for (var i = 0; i < terms.length; i++) {
    terms[i] = terms[i].replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

Apparently, in IE8 and earlier, empty-string matches are ignored by split() when a regex parameter is used. A string parameter works fine:

'axx'.split('x')    // All browsers: ["a", "", ""]
'axx'.split(/x/)    // IE6/7/8: ["a"], all other browsers: ["a", "", ""]
Matt Coughlin
  • 18,666
  • 3
  • 46
  • 59
-1

You're going to have to rewrite the regex.

Try this.

String.prototype.trim = String.prototype.trim || function() {
    return this.replace(/^\s+|\s+$/g, ''); 
}
function split( str ){
    return (""+str).trim().split( /\,/ );
}
Larry Battle
  • 9,008
  • 4
  • 41
  • 55