String split returns an array with more elements than expected (empty elements) String split returns an array with more elements than expected (empty elements) arrays arrays

String split returns an array with more elements than expected (empty elements)


You could add a filter to exclude the empty string.

var string = 'a,b,c,d,e:10.';var array = string.split ('.').filter(function(el) {return el.length != 0});


A slightly easier version of @xdazz version for excluding empty strings (using ES6 arrow function):

var array = string.split('.').filter(x => x);


This is the correct and expected behavior. Given that you've included the separator in the string, the split function (simplified) takes the part to the left of the separator ("a,b,c,d,e:10") as the first element and the part to the rest of the separator (an empty string) as the second element.

If you're really curious about how split() works, you can check out pages 148 and 149 of the ECMA spec (ECMA 262) at http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf