June 18, 2011
Create, Read and Delete Cookies with JavaScript
In this tutorial, I am going to give a JavaScript code samples to create, read and delete the cookies.
Setting a Cookie
function SetCookie(name,value,days) { var now= new Date(); var expDate = new Date(); if (days==null || days==0) days=1; //create date after no of "days" from now expDate.setTime(now.getTime() + 3600000*24*days); //create cookie with name, value and expire date document.cookie=name+"="+escape(value)+";expires="+expDate.toUTCString(); }
Call the above function to set the cookie:
SetCookie("testCookie","testval",30);
The Cookie “testCookie” has the value “testval” and expires in 30 days.
Reading a Cookie
ReadCookie("testCookie"); // Returns value "testval" function ReadCookie(name) { if (name == "") return ""; var strCookie =" " + document.cookie; var idx = strCookie.indexOf(" " + name + "="); if (idx == -1) idx = strCookie.indexOf(";" + name + "="); if (idx == -1) return ""; var idx1 = strCookie.indexOf(";", idx+1); if (idx1 == -1) idx1 = strCookie.length; return unescape(strCookie.substring(idx + name.length+2, idx1)); }
Reading a Cookie With RegExp
This is another version of ReadCookie method using Regular Expression.
function ReadCookie(name) { name = name.replace(/([.\\+\-*:\/?!|^${}()\[\]])/g, '\\$1'); var re = new RegExp('[; ]' + name + '=([^\\s;]*)'); var sMatch = (' ' + document.cookie).match(re); if (name && sMatch) return unescape(sMatch[1]); return ''; }
Deleting a Cookie
To delete a cookie with a given name, set a cookie that has the same name and an expiration date in the past.
SetCookie("testCookie","",-1);
How do you find cookies enabled?
To know whether cookies are enabled, you can set a cookie with non-empty value and then retrieve it. If the retrieved cookie value is the same as you’ve just set, then cookies are enabled. If the retrieved value is an empty string, then cookies are disabled.
3 Comments
Great post..
There is a plugin available which not only supports cookies but it also supports JSON cookies which is quite useful.
http://jquerybyexample.blogspot.com/2012/05/how-to-create-read-and-delete-cookies.html
Thanks a lot…It’s very useful for me.Cheers