The Confusion About the Split() Function of Javascript with an Empty String

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?

1

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

In other words, this is by design, and not an error :)

10

Because you get an array that contains the empty string:

[ "" ]

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

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.

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.

Eliminate any null string.

str.split('{SEPERATOR}').filter(r => r !== 'null')
1

JavaScript split creates an array. That is, your variable, strs = [0]=>"" and its length is 1.

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;
  };
4

try this

javascript gives two arrays by split function, then

var Val = "";
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.