The confusion about the split() function of JavaScript with an empty string
JavascriptSplitJavascript Problem Overview
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?
Javascript Solutions
Solution 1 - Javascript
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 :)
Solution 2 - Javascript
Because you get an array that contains the empty string:
[ "" ]
That empty string is one element. So length
is 1.
Solution 3 - Javascript
Splitting window.location.pathname
Note that on window.location.pathname splitting it will mostly return a length of +1 also.
Lets assume our pathname in this case is: /index.html
.
var str = window.location.pathname.split('/');
It will be split into ["" , "index.html"]
by design, as mentioned here many times before.
What one could do in this case is, strip the leading and trailing /
like so:
var str = window.location.pathname.replace(/^\/|\/$/g, '').split('/');
and end up with the "correct"ed length.
Solution 4 - Javascript
> Description > > 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 > omitted, the array contains one > element consisting of the entire > string. > > Note: When the string is empty, split returns an array containing one > empty string, rather than an empty > array.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
Solution 5 - Javascript
Eliminate any null string.
str.split('{SEPERATOR}').filter(r => r !== 'null')
Solution 6 - Javascript
JavaScript split
creates an array. That is, your variable, strs = [0]=>""
and its length is 1.
Solution 7 - Javascript
I got sick of always checking for a[0] == '' so:
String.prototype.splitPlus = function(sep) {
var a = this.split(sep)
if (a[0] == '') return [];
return a;
};
Corrected version for when element 1 might be null:
String.prototype.splitPlus = function(sep) {
var a = this.split(sep)
if (a[0] == '' && a.length == 1) return [];
return a;
};
Solution 8 - Javascript
try this
javascript gives two arrays by split function, then
var Val = "[email protected]";
var mail = Val.split('@');
if(mail[0] && mail[1]) { alert('valid'); }
else { alert('Enter valid email id'); valid=0; }
if both array contains length greater than 0 then condition will true