Reading Cookies

Course- Javascript >

The function to read the value of a cookie relies heavily on JavaScript’s split() string method that you learned about in section, “Numbers and Strings.” You may recall that split() takes a string and splits it into an array of items, using a specified character to determine where the string should be divided:

myString = "John#Paul#George#Ringo";
var myArray = myString.split('#');                 
                 

The preceding statement would divide string myString into a series of separate parts, cutting the string at each occurrence of the hash (#) character; myArray[0] would contain “John,” myArray[1] would contain “Paul,” and so forth.

Since in document.cookie the individual cookies are divided by the semicolon character, this character is initially used to break up the string returned by document.cookie:

var crumbs = document.cookie.split(';');

You want to search for a cookie of a specific name, so the resulting array crumbs is next searched for any items having the appropriate name= part.

The indexOf() and substring() methods are combined to return the value part of the cookie, which is then returned by the function after using unescape() to remove any encoding:

function getCookie(name) {
var nameEquals = name + "=";
var crumbs = document.cookie.split(';');
for (var i = 0; i < crumbs.length; i++) {
var crumb = crumbs[i];
if (crumb.indexOf(nameEquals) == 0) {
return unescape(crumb.substring(nameEquals.length,
crumb.length));
}
}
return null;
}