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?
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.
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.
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.
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 .
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 :)
Because you get an array that contains the empty string:
[ "" ]
That empty string is one element. So length
is 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With