Skip to content

Instantly share code, notes, and snippets.

@dmitry-korolev
Last active October 10, 2015 17:17
Show Gist options
  • Save dmitry-korolev/810176435b48be16a1de to your computer and use it in GitHub Desktop.
Save dmitry-korolev/810176435b48be16a1de to your computer and use it in GitHub Desktop.
Simple functions to work with cookies. Plain JS.
/**
* @link https://learn.javascript.ru/cookie
*/
function setCookie(name, value, options) {
options = options || {};
var expires = options.expires;
if (typeof expires == "number" && expires) {
var d = new Date();
d.setTime(d.getTime() + expires * 1000);
expires = options.expires = d;
}
if (expires && expires.toUTCString) {
options.expires = expires.toUTCString();
}
value = encodeURIComponent(value);
var updatedCookie = name + "=" + value;
for (var propName in options) {
updatedCookie += "; " + propName;
var propValue = options[propName];
if (propValue !== true) {
updatedCookie += "=" + propValue;
}
}
document.cookie = updatedCookie;
}
function getCookie(name) {
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
}
function deleteCookie(name) {
setCookie(name, "", {
expires: -1
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment