Javascript Cookies

Cookies are small strings that let you store data across page views and
sessions. These are some common uses of cookies:
1. Keeping track of whether the user has logged in to your site
2. Remembering that a user has visited a page before
3. Differentiating between fi rst-time visitors and repeat visitors
Cookies are also sent to the server with every page request. That’s how
the server knows whether the user is logged in. Because cookies add data
to the request and therefore increase the size of the request, cookie data
is limited to 4KB.
The window.document object has a funny little property called cookie.
You can use that object to read and set cookie data.
Setting Cookies
To set a cookie, just assign the name and value to document.cookie
in the following format:
document.cookie = "name=value";
You can set only one cookie at a time, but assigning another value to
document.cookie doesn’t overwrite the previous cookies, unless one of
them shares the same name. You can continue to assign name/value pairs
to document.cookie until you hit the 4KB limit enforced by the browser.
// Adding another cookie
document.cookie = "anotherName=anotherValue";
You should always pass the value part of the string through
encodeURIComponent() to make sure it doesn’t contain any illegal
characters such as spaces, commas, and semicolons.
var cookieValue = "encoded value";
document.cookie = "thirdCookie=" +
encodeURIComponent(cookieValue);
You can also set the following optional parameters that affect the



// This secure cookie will last a year
document.cookie = "name=value;max-age=" + (60*60*24*365) +
";secure;";

You’ll have to use your string manipulation skills to extract a single
cookie’s value from this string. Regular expressions come in handy here.

function getCookie(name) {
// Get each individual cookie by splitting
// on semicolons and possible spaces
var cookies = document.cookie.split(/;\s*/);
// Make a regular expression to match the name
// and value in a subpattern
var pattern = new RegExp("\\b" + name + "=(.*)");
// Check each cookie until you fi nd a match
for (var i = 0, l = cookies.length; i < l; i++) {
var match = cookies[i].match(pattern);
if (match) {
return decodeURIComponent(match[1]);
}
}
}