Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
19
rated 0 times [  23] [ 4]  / answers: 1 / hits: 60767  / 12 Years ago, thu, october 11, 2012, 12:00:00

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?


More From » arrays

 Answers
8

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


[#82611] Wednesday, October 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dusty

Total Points: 739
Total Questions: 97
Total Answers: 85

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;