My first question on Stack :)
I wonder why the following statement :
'5 '.split(' ')
will return an array of length 2 with ['5', '']
There is nothing after the ' ' symbol. Basically, everytime Javascript found the separator in a string, if the separator is found multiple time, he will create empty elements :
'5 '.split(' ')
['5', '', '', '']
I was expecting ['5']
for the 1 exemple.
CodePudding user response:
If you're splitting '5 '
with
as the separator, then returning two substrings ('5'
and an empty string) is the correct result because that is what's on either side of the separator. If it had returned a list containing only one element and you had tried to join
the list back together into the original string, you would get the wrong result.
var elements = ['5'];
console.log(elements.join(' '));
But joining the result of split does give back the original string.
var elements = '5 '.split(' ');
console.log(elements);
console.log(elements.join(' '));