Skip to content

Instantly share code, notes, and snippets.

@detj
Last active August 29, 2015 14:02
Show Gist options
  • Save detj/204453cbcbf9bd3a46ec to your computer and use it in GitHub Desktop.
Save detj/204453cbcbf9bd3a46ec to your computer and use it in GitHub Desktop.
Client side cookie manipulation
/**
* Get a cookie by key
*/
function getCookieItem(sKey) {
if (!sKey || !this.hasCookieItem(sKey)) { return null; }
return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
}
/**
* Set a cookie
*/
function setCookieItem(sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Tue, 19 Jan 2038 03:14:07 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toGMTString();
break;
}
}
document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
}
/**
* Delete cookie by key
*/
function removeCookieItem(sKey, sPath) {
if (!sKey || !this.hasCookieItem(sKey)) { return; }
document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sPath ? "; path=" + sPath : "");
}
/**
* Check existence of cookie by key
*/
function hasCookieItem(sKey) {
return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment