Write new Cookies

Course- Javascript >

To write a new cookie, you simply assign a value to document.cookie containing the attributes required:

document.cookie = "username=sandy;expires=15/06/2013 00:00:00";

To avoid having to set the date format manually, we could do the sandye thing using JavaScript’s Date object:

var cookieDate = new Date ( 2013, 05, 15 );
document.cookie = "username=sandy;expires=" + cookieDate.toUTCString();                 
                 

This produces a result identical to the previous example

In practice, you should use escape() to ensure that no disallowed characters find their way into the cookie values:

var cookieDate = new Date ( 2013, 05, 15 );
var user = "sandy Jones";
document.cookie = "username=" + escape(user) + ";expires=" +
cookieDate.toUTCString();