Javascript: Simple cookie managing

Just a code snippet to manage cookies in a simple way:

function cookie(name,value,expire) {
	var D = document,d,r,c,n,f;
	if (void 0 != value) {
		d = new Date;
		d.setDate(d.getDate()+expire);
		D.cookie = name + "=" + escape(value) + ((null==expire) ? "" : ";expires=" + d.toGMTString());
	} else {
		r = [], c = D.cookie.split(";");
		for (n = 0; n < c.length; n++) (f = c[n].match(RegExp("^\\s*"+name+"=\\s*(.*?)\\s*$"))) && r.push(f[1]);
		return r[0]?r[0]:!1;
	}
}

You can set, read or delete cookie:

cookie(name,val);
cookie(name);
cookie(name,'',-1);

GitHub gist available here.

Leave a Reply