js cookie 使用

 1 function setCookie(key, value, expires = 1) {
 2     var days = expires;
 3     var exp = new Date();
 4     exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
 5     document.cookie = key + "=" + escape(value) + ";expires=" + exp.toGMTString();
 6 }
 7 
 8 function getCookie(key) {
 9     var arr, reg = new RegExp("(?<=(?:^|\\s)" + key + "=).+?(?=(?:;|$))", 'g');
10     if (arr = document.cookie.match(reg)) {
11         return unescape(arr[0]);
12     } else {
13         return null;
14     }
15 }
16 
17 function removeCookie(key) {
18     var exp = new Date();
19     exp.setTime(exp.getTime() - 1);
20     var cval = getCookie(key);
21     if (cval != null) {
22         document.cookie = key + "=" + escape(cval) + "; expires=" + exp.toGMTString();
23         return true;
24     } else {
25         return false;
26     }
27 }
28 
29 export {
30     setCookie,
31     getCookie,
32     removeCookie,
33 }

 

posted @ 2023-08-10 11:49  万物有序  阅读(92)  评论(0编辑  收藏  举报