67

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
  • 10
    you could do a simple .split('...').filter(Boolean) if you didnt care about falsy values. Commented Nov 24, 2018 at 14:24

9 Answers 9

81

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

Sign up to request clarification or add additional context in comments.

10 Comments

When would this 'design choice' be better than returning an empty array?
It's for consistency. '&'.split('&') returns 2 empty strings; '&&'.split('&') returns 3; etc.
@Spongman it is not an error, it makes perfect sense. If it worked any other way it would be inconsistent, and inconsistency is arguably the worst sin in programming.
Let's think about this by example. Imagine you have a text file with three lines and you splitting it at newlines: "One\n\nThree".split('\n') which is ["One","","Three"]. Notice that the second line is blank (""). If the text file has only one line, "One".split('\n') the result is ["One"]. So logically, "".split('\n') should be [""] since there is still one line. The line is blank, but we saw before that a blank line is "". In some languages such as C# there is an option to remove empty entries from the output, but JavaScript does not offer it.
You could try str.split('&').filter(o=>o) which would eliminate any empty string in the array and in your case, it would return an empty array!
|
10

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.

Comments

8

Because you get an array that contains the empty string:

[ "" ]

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

Comments

6

Eliminate any null string.

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

2 Comments

That seems to be checking for a string that has a value of 'null'. This works> .filter(r => r !== '')
Testing for r is enough: filter(r => r) // Empty string, undefined, null, ...
4

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

Comments

2

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 Comments

This will fail for ",a,b,c".splitPlus(","), though - returning [] when it should return ["", "a", "b", "c"]. You have to check for the array length as well.
add && a.length > 0 to your if condition.
@aggaton I added the corrected version with : if (a[0] == '' && a.length == 1) return [];
why not ===? .
0

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

Comments

0

invent explode/implode (like PHP)

Object.defineProperty(String.prototype,"explode",{
    value: function (sep = '') {
        return this.length ? this.split(sep) : [];
    }
});

so empty-string goes to empty-array

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.