59

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?

1
  • yeah i really hate it when one must omit ending separators. so annoying when trying to write consistent code or values or just editing a strict-type json
    – oriadam
    Commented Jun 24, 2020 at 17:18

11 Answers 11

105

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});
2
  • 5
    Please note filter() is an ECMAScript 5 array function so additional code would need to be included to use this functionality if your browser doesn't support this. Please look here for more info and the code needed to implement this method. Commented Oct 11, 2012 at 9:20
  • 14
    This should be the accepted answer because it solves the problem - returns what is expected - instead of linking to some docs.
    – MrCroft
    Commented Jun 5, 2017 at 11:18
49

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

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

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

2
  • 6
    Here is a direct link to the method specification: es5.github.com/#x15.5.4.14. Commented Oct 11, 2012 at 9:37
  • "the split function takes the part to the left of the separator as the first element" – THIS answered the WHY this happens.
    – Avatar
    Commented May 7, 2022 at 15:45
19

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

4

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

3
  • This simply returns a string "a,b,c,d,e:10", not an array, which is why the length is 1.
    – caseyjhol
    Commented Dec 30, 2016 at 19:20
  • Hi @caseyjhol, the length of the string would be 12 not 1. the call to split always returns an array so the length is 1. It's my intention here to show that the call to split('.') returns an array of length 1. My answer is correct.
    – chim
    Commented Jan 6, 2017 at 9:06
  • 1
    You're right - I misread the original question and thought he was trying to convert it to an array using the comma as a separator.
    – caseyjhol
    Commented Jan 23, 2017 at 22:10
1

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.

1

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

// ↪ [""]
0

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

0

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"]
0

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?

-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

Not the answer you're looking for? Browse other questions tagged or ask your own question.