Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The confusion about the split() function of JavaScript with an empty string

First I set a variable, and set it to empty:

var str = ""; 

Then I split it through "&":

var strs = str.split('&'); 

In the end, I show strs's length:

alert( strs.length); 

It alert "1".

But I assign nothing to the 'str' variable. Why does it still have a length, should't it be zero?

like image 778
hh54188 Avatar asked Mar 02 '11 08:03

hh54188


People also ask

What happens if you split an empty string?

The natural consequence is that if the string does not contain the delimiter, a singleton array containing just the input string is returned, Second, remove all the rightmost empty strings. This is the reason ",,,". split(",") returns empty array.

What is split () function in string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

What does the split function do in JavaScript?

split() The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.

What is the use of empty string in JavaScript?

Use the === Operator to Check if the String Is Empty in JavaScript. We can use the strict equality operator ( === ) to check whether a string is empty or not. The comparison data==="" will only return true if the data type of the value is a string, and it is also empty; otherwise, return false .


2 Answers

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 :)

like image 93
Martin Jespersen Avatar answered Sep 20 '22 21:09

Martin Jespersen


Because you get an array that contains the empty string:

[ "" ] 

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

like image 22
BoltClock Avatar answered Sep 20 '22 21:09

BoltClock