Reputation:
The following gives an array of length 1 with an empty string in it. Why?
var tokens = AN_EMPTY_STRING.split("ANY_REGEX");
I expect this should give an array with no elements in it. What is the logic of this?
Upvotes: 1
Views: 38
Reputation: 4594
This is just how split works (from the docs)
The split() method returns the new array.
When found, separator is removed from the string and the substrings are returned in an array. If separator is not found or is omitted, the array contains one element consisting of the entire string. If separator is an empty string, str is converted to an array of characters.
It doesn't matter what the seperator is, if it's there and not found, an ''
(empty string) will return it's contents in the form of an array element so your return value will always be atleast ''
(an empty string).
there seem to be some odd things here (IMO anyway)
''.split('')
returns []
with a .length
of 0
''.split(/b/)
returns [""]
with a .length
property of 1
since the seperator (b
) isn't in the string (working as intended according to the docs)
Upvotes: 2