The confusion about the split() function of JavaScript

From the MDC doc center:

Note: When the string is empty, split returns an array containing one empty string, rather than an empty array.

Read the full docs here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split

In other words, this is by design, and not an error :)


Because you get an array that contains the empty string:

[ "" ]

That empty string is one element. So length is 1.


Splitting window.location.pathname

Note that on window.location.pathname splitting it will mostly return a length of +1 also.

Lets assume our pathname in this case is: /index.html.

var str = window.location.pathname.split('/');

It will be split into ["" , "index.html"] by design, as mentioned here many times before.

What one could do in this case is, strip the leading and trailing / like so:

var str = window.location.pathname.replace(/^\/|\/$/g, '').split('/');

and end up with the "correct"ed length.