Reading Cookies

When you use the cookie property in a JavaScript expression, the value it returns is a string that contains all the cookies that apply to the current document.[53] The string is a list of name = value pairs separated by semicolons, where name is the name of a cookie and value is its string value. This value does not include any of the attributes that may have been set for the cookie. To determine the value of a particular named cookie, you can use the String.indexOf( ) and String.substring( ) methods, or you can use String.split( ) to break the string into individual cookies.

Once you have extracted the value of a cookie from the cookie property, you must interpret that value based on whatever format or encoding was used by the cookie’s creator. For example, the cookie might store multiple pieces of information in colon-separated fields. In this case, you would have to use appropriate string methods to extract the various fields of information. Don’t forget to use the unescape( ) function on the cookie value if it was encoded using the escape( ) function.

The following code shows how you might read the cookie property, extract a single cookie from it, and use the value of that cookie:

// Read the cookie property. This returns all cookies for this document. var allcookies = document.cookie; // Look for the start of the cookie named "version" var pos = allcookies.indexOf("version="); // If we find a cookie by that name, extract and use its value if (pos != -1) ...

Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.