Document.cookies properties

Course- Javascript >

Cookies in JavaScript are stored and retrieved by using the cookie property of the document object.

Each cookie is essentially a text string consisting of a name and a value pair, like this:

username=sandy

When a web page is loaded into your browser, the browser marshals all of the cookies available to that page into a single string-like property, which is available as document.cookie. Within document.cookie, the individual cookies are separated by semicolons:

username=sandy;location=INDIA;status=fullmember;

Escaping and Unescaping Data

Cookie values may not include certain characters. Those disallowed include semicolons, commas, and whitespace characters such as space and tab. Before storing data to a cookie, you need to encode the data in such a way that it will be stored correctly.

You can use the JavaScript escape() function to encode a value before storing it, and the corresponding unescape() function to later recover the original cookie value.

The escape() function converts any non-ASCII character in the string to its equivalent two- or four-digit hexadecimal format—so a blank space is converted into %20, and the ampersand character (&) to %26.

For example, the following code snippet writes out the original string saved in variable str followed by its value after applying the escape() function:

var str = 'Here is a (short) piece of text.';
document.write(str + '
' + escape(str));

The output to the screen would be

Here is a (short) piece of text.
Here%20is%20a%20%28short%29%20piece%20of%20text.                 
                 

Notice that the spaces have been replaced by %20, the opening parenthesis by %28, and the closing parenthesis by %29.

All special characters, with the exception of *, @, -, _, +, ., and /, are encoded.