Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does split function look like?

I came across this statement :

userName = document.cookie.split("=")[1];

after reading about split statement here at w3schools. which says that syntax of split is string.split(separator, limit). Then what does the square bracket after first parens. mean ? If this is true what does split function look like ?

like image 217
saplingPro Avatar asked Apr 27 '26 10:04

saplingPro


2 Answers

String.split(separator, limit) returns an array. In Javascript, you can access array values by index using the square brackets. Arrays are zero-based, 0 is the first element, 1 the second and so on.

The equivalent of your code would be:

var arr = document.cookie.split("=");
userName = arr[1];

This separates the document.cookie by the equal-sign (=) and takes the second element (index 1) from it. document.cookie is a special property (datatype: String) of the document object which contains all cookies of a webpage, separated by the ; character. E.g. if document.cookie contains name=Adam, the array arr will contain the values name and Adam. The second one is stored in userName.

Note that if the cookie contains multiple values, or if the value contains multiple equal-signs, it won't work. Consider the next cases:

  • document.cookie contains name=Adam; home=Nowhere. Using the above code, this would make userName contain Adam; home because the string is separated by the equal-sign, and then the second value is taken.
  • document.cookie contains home=Nowhere; name=Adam. This would result in userName containing Nowhere; name
  • document.cookie contains name=Adam=cool. In this case, userName would be Adam and not Adam=cool.

Also, w3schools is not that reliable. Use more authorative sources like the Mozilla Developer Network:

  • document.cookie
  • String.split
  • Array
like image 198
Lekensteyn Avatar answered Apr 28 '26 23:04

Lekensteyn


The split function returns an array of strings split by the given separator. With the square bracket you are accessing the nth element of that (returned) array.

If you are familiar with Java, its the same behavior as the String.split() method there.

like image 20
Saket Avatar answered Apr 29 '26 00:04

Saket



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!