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?
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.
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.
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.
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.
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With