Reading a Cookie (basic JavaScript)

JavaScript FAQ | JavaScript Cookies FAQ  

Question: How do I read a cookie with a given name?

Answer: Here is a function for reading a cookie cookieName that has been set by SetCookie. It relies on the standard string manipulation methods: substring() and indexOf(). The function runs without errors even in very old browsers with the earliest implementations of JavaScript:

function ReadCookie(cookieName) {
 var theCookie=" "+document.cookie;
 var ind=theCookie.indexOf(" "+cookieName+"=");
 if (ind==-1) ind=theCookie.indexOf(";"+cookieName+"=");
 if (ind==-1 || cookieName=="") return "";
 var ind1=theCookie.indexOf(";",ind+1);
 if (ind1==-1) ind1=theCookie.length; 
 return unescape(theCookie.substring(ind+cookieName.length+2,ind1));
Cookie Name: 

A note on reliability: Why did we need to prefix the cookie with a space (" "+) or a semicolon (";"+) in the beginning of the function? Here is why: to avoid false matches. Assume that we succefully created one cookie named MyCookie. Now try reading some other cookies; specifically, try cookie names e or ie or okie... These other cookies presumably do not exist; however, a buggy version of ReadCookie without the highlighted safeguards would still return a non-empty value (most likely, the same value as for MyCookie) - as if all of the above cookies were present! We thus see that there are important special cases where a quick-and-dirty reader function may easily fail.

Difficult special cases like this manifest themselves especially when there are two or more semicolon-separated cookies in the document.cookie string - and that's exactly what may happen on big websites in real life. What if we must read not only cookies set by our own scripts, but also those cookies that came from various server-side applications? Let us consider document.cookie examples that we might want to handle with our cookie-reader function.

Examples of document.cookie:
name1=value1; name2=value2; name3=value3; name4=value4; . . .  //an easy case
Just_a_value; name2=name1=a&b=c; name1=value1; e1=v1; e2=v2;   //more difficult

Here are the pitfalls:
(1) The cookieName argument may hold a substring of some other existing cookie name(s)
(2) cookieName may hold a substring of another cookie's value
(3) Cookies may have a complex multilevel structure, e.g. name2=a=b&b=1&&c=d;...
(4) Cookies in document.cookie may or may not have the name=value format
(5) There might be a (rare) requirement to support commas as well as semicolons in the role of cookie separators.

Next, we'll write another function for reading a cookie using regular expressions. As you will see, the RegExp-based version turns out to be shorter and easier to modify, but somewhat less readable. Please read on...

Copyright © 1999-2011,