export function cookie(cookieName, cookieValue, day) {
function readCookie (name: string) {
const reg = new RegExp(`(^| )${name}=([^;]*)(;|$)`);
const matched = document.cookie.match(reg);
const arr = matched;
if (arr) {
return unescape(arr[2]);
}
return null;
}
function setCookie(name, value, time) {
const Days = time || 30;
const exp = new Date();
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
document.cookie = `${name}=${escape(value)};expires=${exp.toUTCString()}`;
}
if (cookieName && cookieValue) {
// set cookie
setCookie(cookieName, cookieValue, day);
return cookieValue;
} if (cookieName && cookieValue === null) {
// delete cookie
setCookie(cookieName, '', -1);
return cookieValue;
} if (cookieName) {
// read cookie
return readCookie(cookieName);
}
return null;
}
ts 版本
export function cookie(cookieName:string, cookieValue?:string, day?:number) {
function readCookie (name: string) {
const reg = new RegExp(`(^| )${name}=([^;]*)(;|$)`);
const matched = document.cookie.match(reg);
const arr = matched;
if (arr) {
return unescape(arr[2]);
}
return null;
}
function setCookie(name:string, value:string, time?:number) {
const Days = time || 30;
const exp = new Date();
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
document.cookie = `${name}=${escape(value)};expires=${exp.toUTCString()}`;
}
if (cookieName && cookieValue) {
// set cookie
setCookie(cookieName, cookieValue, day);
return cookieValue;
} if (cookieName && cookieValue === null) {
// delete cookie
setCookie(cookieName, '', -1);
return cookieValue;
} if (cookieName) {
// read cookie
return readCookie(cookieName);
}
return null;
}