Reading a Cookie (basic JavaScript)
Question: How do I read a cookie with a given name?
Answer:
Here is a function for reading a cookie 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)); } A note on reliability:
Why did we need to prefix the cookie with
a space (
Difficult special cases like this manifest themselves especially when there are two or more
semicolon-separated cookies in the |
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
cookieName
argument may hold a substring of some other existing cookie name(s)
cookieName
may hold a substring of another cookie's value
name2=a=b&b=1&&c=d;...
document.cookie
may or may not have the name=value
format
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, JavaScripter.net.