Why the code below returns 1? That doesn't make sense.
var length = "".split(" ").length;
console.log(length);
Why the code below returns 1? That doesn't make sense.
var length = "".split(" ").length;
console.log(length);
Share
Improve this question
edited Jul 1, 2018 at 19:48
Ivar
6,86812 gold badges56 silver badges67 bronze badges
asked Jul 1, 2018 at 19:39
Tomás Hugo AlmeidaTomás Hugo Almeida
1301 silver badge8 bronze badges
1
- 4 Possible duplicate of What does split() returns if the string has no match – Ivar Commented Jul 1, 2018 at 19:52
4 Answers
Reset to default 6Because split
will return original string
if there wasn't split char
in that string
.
like:
"".split(" ")
// [""]
"a".split(" ")
// ["a"]
String.prototype.split()
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.
split
returns array [""]
which length is 1
.
split
will "break up" the string when a match is found, so:
"something".split("different");
Will not break up the string, resulting in:
["something"]
The same applies to an empty string.
Simply put, it will split the string at every " "
, though since the string doesn't have any " "
, it will be an array with only one item holding the original string itself, no matter that string is empty or not, hence length is 1.
Below samples shows the length if there were just one " "
in the string, ending in ["",""]
.
console.log( "".split("").length );
console.log( "".split(" ").length );
console.log( " ".split(" ").length );