1

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?

3
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Dec 22, 2015 at 1:26
  • 1
    If separator is not found or is omitted, the array contains one element consisting of the entire string - so you get an array with one element consisting of the entire string, which is an empty string. Commented Dec 22, 2015 at 1:27
  • 1
    Note: When the string is empty, split() returns an array containing one empty string, rather than an empty array. If the string and separator are both empty strings, an empty array is returned. Commented Dec 22, 2015 at 1:27

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

3 Comments

@Solver "If the string and separator are both empty strings" - you're passing in a regex right? e.g. .split(/b/) without any " double quotes around the expression right?
If this answer solved your problem, could you mark it as accepted (green tick below the voting section of the post) so that other users know your issue is solved?
@Solver I was confused, my bad - you said something about a yellow note which is exactly the color of a quote on SO... It also happens to be the same color of the note on Mozilla's docs page - That's where I failed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.