Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does .split() return if the string has no match?

Tags:

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?

like image 586
Vikram Anand Bhushan Avatar asked Dec 29 '14 11:12

Vikram Anand Bhushan


People also ask

Why does split return empty string?

In the case of splitting an empty string, the first mode (no argument) will return an empty list because the whitespace is eaten and there are no values to put in the result list. In contrast, the second mode (with an argument such as \n ) will produce the first empty field.

What does the string split method return?

The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings.

What does split () return in Python?

The string manipulation function in Python used to break down a bigger string into several smaller strings is called the split() function in Python. The split() function returns the strings as a list.

Can string split return null?

The Javadoc for split(String regex) does not indicate that null cannot be returned. @Paul: No, but if null could be returned, it (or the Pattern#split docs) would say so.


1 Answers

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.

like image 92
paxdiablo Avatar answered Sep 30 '22 07:09

paxdiablo