Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
79
rated 0 times [  84] [ 5]  / answers: 1 / hits: 52038  / 10 Years ago, mon, december 29, 2014, 12:00:00

In this JavaScript code if the variable data does not have that character . then what will split return?



x = data.split('.');


Will it be an array of the original string?


More From » javascript

 Answers
20

Yes, as per ECMA262 15.5.4.14 String.prototype.split (separator, limit), if the separator is not in the string, it returns a one-element array with the original string in it. The outcome can be inferred from:




Returns an Array object into which substrings of the result of converting this object to a String have been stored. The substrings are determined by searching from left to right for occurrences of separator; these occurrences are not part of any substring in the returned array, but serve to divide up the String value.




If you're not happy inferring that, you can follow the rather voluminous steps at the bottom and you'll see that's what it does.



Testing it, if you type in the code:



alert('paxdiablo'.split('.')[0]);


you'll see that it outputs paxdiablo, the first (and only) array element. Running:



alert('pax.diablo'.split('.')[0]);
alert('pax.diablo'.split('.')[1]);


on the other hand will give you two alerts, one for pax and one for diablo.


[#68364] Wednesday, December 24, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
domeniccolti

Total Points: 276
Total Questions: 98
Total Answers: 93

Location: India
Member since Fri, May 13, 2022
2 Years ago
domeniccolti questions
Mon, Oct 18, 21, 00:00, 3 Years ago
Thu, Oct 14, 21, 00:00, 3 Years ago
Thu, Jul 15, 21, 00:00, 3 Years ago
Sat, Oct 24, 20, 00:00, 4 Years ago
Thu, Sep 3, 20, 00:00, 4 Years ago
;