Reading cookies works significantly differently from writing cookies. While we can write each cookie separately simply by setting document.cookie to the values we want the new (or replacement) cookie to have, JavaScript does not provide a way to access the cookies separately when reading them but instead if you try to read the value back from document.cookie you get all of the cookies passed to the current page as one long string.
So in order to actually access the individual cookies that are passed to the web page we need to write our own code that will split up the content of document.cookie into the individual cookies. The simplest way to do this is to create a cookie object where each individual cookie exists as a property of the cookie object. The function in this example code does exactly that while the last line of the example code shows how we can test if a cookie with the name 'user' exists and if so then assign the value to a field of that name.
var cookie, user;
allCookies = function() {
var cr, ck, cv;
cr = []; if (document.cookie != '') {
ck = document.cookie.split('; ');
for (var i=ck.length - 1; i>= 0; i--) {
cv = ck.split('=');
cr[ck[0]]=ck[1];
}
}
return cr;
};
cookie = allCookies();
if (cookie.user != null) user = cookie.user;
