欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JS 操作 Cookie

程序员文章站 2022-12-19 21:59:58
获取 Cookie: 设置 Cookie: 删除 Cookie: ......

获取 Cookie:

/**
 * 获取 Cookie
 * @param {String} name Cookie 名称
 */
function getCookie (name) {
  var reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  var arr = document.cookie.match(reg)
  if (arr) {
    return (arr[2]);
  }

  return null;
};

设置 Cookie:

/**
 * 设置 Cookie
 * @param {String} name Cookie 名称
 * @param {String} value Cookie 值
 * @param {Number} exdays Cookie 过期时间
 */
function setCookie  (name, value, exdays) {
  var dateNow = new Date();
  dateNow.setTime(dateNow.getTime() + (exdays * 24 * 60 * 60 * 1000));
  var expires = 'expires=' + d.toUTCString();
  document.cookie = name + '=' + value + '; ' + expires;
};

删除 Cookie:

/**
 * 删除 Cookie
 * @param {String} name Cookie 名称
 */
function delCookie  (name) {
  var dateNow = new Date();
  dateNow.setTime(dateNow.getTime() - 1);
  var currentCookie = getCookie(name);
  if (currentCookie != null) {
    document.cookie = name + "=" + currentCookie + ";expires=" + dateNow.toGMTString();
  }
};