String split returns an array with more elements than expected (empty elements)

JavascriptArraysStringSplit

Javascript Problem Overview


I don't understand this behaviour:

var string = 'a,b,c,d,e:10.';
var array = string.split ('.');

I expect this:

console.log (array); // ['a,b,c,d,e:10']
console.log (array.length); // 1

but I get this:

console.log (array); // ['a,b,c,d,e:10', '']
console.log (array.length); // 2

Why two elements are returned instead of one? How does split work?

Is there another way to do this?

Javascript Solutions


Solution 1 - Javascript

You could add a filter to exclude the empty string.

var string = 'a,b,c,d,e:10.';
var array = string.split ('.').filter(function(el) {return el.length != 0});

Solution 2 - Javascript

A slightly easier version of @xdazz version for excluding empty strings (using ES6 arrow function):

var array = string.split('.').filter(x => x);

Solution 3 - Javascript

This is the correct and expected behavior. Given that you've included the separator in the string, the split function (simplified) takes the part to the left of the separator ("a,b,c,d,e:10") as the first element and the part to the rest of the separator (an empty string) as the second element.

If you're really curious about how split() works, you can check out pages 148 and 149 of the ECMA spec (ECMA 262) at http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

Solution 4 - Javascript

Use String.split() method with Array.filter() method.

var string = 'a,b,c,d,e:10.';
var array = string.split ('.').filter(item => item);

console.log(array); // [a,b,c,d,e:10]
console.log (array.length); // 1

Solution 5 - Javascript

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split

trim the trailing period first

'a,b,c,d,e:10.'.replace(/\.$/g,''); // gives "a,b,c,d,e:10"

then split the string

var array = 'a,b,c,d,e:10.'.replace(/\.$/g,'').split('.');

console.log (array.length); // 1

Solution 6 - Javascript

That's because the string ends with the . character - the second item of the array is empty.

If the string won't contain . at all, you will have the desired one item array.

The split() method works like this as far as I can explain in simple words:

  1. Look for the given string to split by in the given string. If not found, return one item array with the whole string.
  2. If found, iterate over the given string taking the characters between each two occurrences of the string to split by.
  3. In case the given string starts with the string to split by, the first item of the result array will be empty.
  4. In case the given string ends with the string to split by, the last item of the result array will be empty.

It's explained more technically here, it's pretty much the same for all browsers.

Solution 7 - Javascript

According to MDN web docs:

> Note: When the string is empty, split() returns an array containing > one empty string, rather than an empty array. If the string and > separator are both empty strings, an empty array is returned.

const myString = '';
const splits = myString.split();

console.log(splits); 

// ↪ [""]

Solution 8 - Javascript

Well, split does what it is made to do, it splits your string. Just that the second part of the split is empty.

Solution 9 - Javascript

Because your string is composed of 2 part :

1 : a,b,c,d,e:10

2 : empty

If you try without the dot at the end :

var string = 'a,b,c:10';
var array = string.split ('.');

output is :

["a,b,c:10"]

Solution 10 - Javascript

You have a string with one "." in it and when you use string.split('.') you receive array containing first element with the string content before "." character and the second element with the content of the string after the "." - which is in this case empty string.

So, this behavior is normal. What did you want to achieve by using this string.split?

Solution 11 - 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWilkView Question on Stackoverflow
Solution 1 - JavascriptxdazzView Answer on Stackoverflow
Solution 2 - JavascriptmarmorView Answer on Stackoverflow
Solution 3 - JavascriptIngoView Answer on Stackoverflow
Solution 4 - JavascriptRohìt JíndalView Answer on Stackoverflow
Solution 5 - JavascriptchimView Answer on Stackoverflow
Solution 6 - JavascriptShadow Wizard Says No More WarView Answer on Stackoverflow
Solution 7 - JavascriptRuslan KorkinView Answer on Stackoverflow
Solution 8 - Javascriptw01k3View Answer on Stackoverflow
Solution 9 - JavascriptMyBoonView Answer on Stackoverflow
Solution 10 - JavascriptMiljan VranicView Answer on Stackoverflow
Solution 11 - Javascriptbhargav 3vediView Answer on Stackoverflow