Illegal characters

Cookies, because of the way they store information, cannot allow certain characters inside the value property. The two most obvious examples are semicolons and spaces. If you used a semicolon or a space, the browser would probably misinterpret the string and return an incorrect value (at best).

The simplest way around this is to use an encoding scheme for the strings. For example, space could be replaced by the '%' symbol, and then changed back when reading the cookie.

If this sounds like more effort than it's worth, don't worry - JavaScript has methods to encode and decode strings. The escape() and unescape() functions (they are not bound to any object), will replace illegal characters in a string with legal characters, and then switch them back.

Combining the escape() function with the previous code, we can write a general-purpose utility for creating cookies that expire in one year's time:

function setCookie(name, value)
{
var expires=new Date();
expires.setYear(expires.getYear() + 1);

var cookieString = name + "=" + escape(value) + "; expires=";
cookieString += expires.toGMTString();

document.cookie = cookieString;
}