Design & Download
Your JS Library
in Seconds!!!

Snippet: Cookies

Written by Christopher West (cwest) on October 29, 2015.
Get, set and remove cookies.
function setCookie(name, value, opt_options) {
  opt_options = opt_options || {};
  // Set the name/value pair.
  var expires = opt_options.expires,
    path = opt_options.path,
    domain = opt_options.domain,
    secure = opt_options.secure,
    maxAge = opt_options['max-age'] || opt_options.maxAge;
  document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value)
    + (expires ? "; expires=" + (new Date(expires)).toGMTString() : "")
    + (path ? "; path=" + path : "; path=/")
    + (domain ? "; domain=" + opt_options.domain : "")
    + (secure ? "; secure" : "");
}
function getCookie(name, opt_defaultValue) {
  if(typeOf(name, 'RegExp')) {
    var ret = getCookie();
    for(var key in ret) {
      if(!name.test(key)) {
        delete ret[key];
      }
    }
  }
  else if(name == undefined) {
    var ret = {};
    document.cookie.replace(/(?:^|;\s*)(.+?)(?=;\s*|$)/g, function($0, $1) {
      $1 = $1.match(/(.*?)=(.*)/);
      ret[decodeURIComponent($1[1])] = decodeURIComponent($1[2]);
    });
  }
  else {
    name = document.cookie.match(new RegExp("(?:^|;\\s*)" + encodeURIComponent(name) + "=(.*?)(?:;\\s*|$)"));
    if(name) {
      var ret = decodeURIComponent(name[1]);
    }
  }
  return ret == undefined ? opt_defaultValue : ret;
}
function removeCookie(name, opt_options) {
  var key, ret = getCookie(name), cookies;
  if(ret && typeOf(ret, "String")) {
    (cookies = {})[name] = ret;
  }
  else {
    cookies = ret;
  }
  opt_options = opt_options || {};
  for(key in cookies) {
    if (has(cookies, key)) {
      setCookie(key, "", {
        path: opt_options.path,
        domain: opt_options.domain,
        secure: opt_options.secure,
        expires: new Date(0)
      });
    }
  }
  return ret;
}

Gives you the ability to use the following functions for getting, setting, and removing cookies: