获取cookie的值,设置cookie,删除cookie

关于更多日常使用的公共类的操作方法,可以关注下小滑轮网站

/**
 * 获取cookie 里的值
 * @param {String} key
 */
export const getCookie = (key) => {
  const arr = document.cookie.match(new RegExp(`(^| )${key}=([^;]*)(;|$)`));
  if (arr != null) return unescape(arr[2]);
  return null;
}

/**
 * 设置cookie
 * @param name
 * @param value
 * @param day expires的时间
 */
function setCookie (name, value, day) {
    let setting = arguments[0];
    if (Object.prototype.toString.call(setting).slice(8, -1) === 'Object'){
        for (let i in setting) {
            let oDate = new Date();
            oDate.setDate(oDate.getDate() + day);
            document.cookie = i + '=' + setting[i] + ';expires=' + oDate;
        }
    }else{
        let oDate = new Date();
        oDate.setDate(oDate.getDate() + day);
        document.cookie = name + '=' + value + ';expires=' + oDate;
    }

}

/** 
 * 删除cookie
 */
function removeCookie (name) {
    setCookie(name, 1, -1);
}

philips
719 声望177 粉丝

前端程序员