ma jack
ma jack

Reputation: 39

Confusion of JavaScript split() method

split method confusion

enter image description here

"aba".split("a") // ["", "b", ""]

"baab".split("a") // ["b", "", "b"]

Why is there an empty item in the result returned by the split method

Upvotes: 0

Views: 64

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074178

"aba".split("a") gives you ["", "b", ""] because the separator (a) appears at the beginning and end of the string. So conceptually there's a blank string prior to the first separator, and a blank string after the last separator.

"baab".split("a") gives you ["b", "", "b"] because there's conceptually a blank string between the two separators in the middle.


In a comment you've asked:

I have a question is where the blank string exists in the string.

Just prior to the separator that's at position 0.

You can find the full details, as always, in the specfication, but MDN's page may be easier to read.

Consider this: If "aba".split("a") gave you ["b"] instead of ["", "b", ""], how would you know that there were any separators in the string at all? "b".split("a") would also give you ["b"].

Upvotes: 3

Related Questions