Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 756
Wilk Avatar asked Oct 11 '12 09:10

Wilk


People also ask

Can string split return empty array?

If the delimiter is an empty string, the split() method will return an array of elements, one element for each character of string. If you specify an empty string for string, the split() method will return an empty string and not an array of strings.

Does split return an array?

The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.

What happens if you split an empty string?

The natural consequence is that if the string does not contain the delimiter, a singleton array containing just the input string is returned, Second, remove all the rightmost empty strings. This is the reason ",,,". split(",") returns empty array.

What is the purpose of the split on a string?

Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.


1 Answers

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}); 
like image 57
xdazz Avatar answered Sep 25 '22 07:09

xdazz