首页 > cookie和url参数获取的常规实用方法合集(ES6)

cookie和url参数获取的常规实用方法合集(ES6)

//获取某一个cookie的值
const getCookie = key => {var k = key, dc = document.cookie;if (dc.length > 0) {var s = dc.indexOf(k + "=");if (s != -1) {s = s + k.length + 1;var e = dc.indexOf(";", s);(e === -1 && (e = dc.length));return unescape(dc.substring(s, e));}}return "";};//获取某一个所有cookie的值,并返回对象
const getAllCookes = () => {var arr = unescape(document.cookie).split("; "), o = {};for (var i = 0, len = arr.length; i < len; i++) {var a = arr[i], index = a.indexOf("="), b = a.substr(0, index), c = a.substr(index + 1);o[b] = c;}return o;};//设置某一个cookie的值
const setCookie = (key, val, seconds = 24 * 60 * 60, path, domain) => {if (val == null || val == undefined) return;var k = key, s = seconds, e = new Date();e.setSeconds(e.getSeconds() + s);val instanceof Array && (val = val.join("||")), val instanceof Object && (val = JSON.stringify(val));document.cookie = `${k}=${escape(val.toString())}${s == null ? "" : ";expires=" + e.toGMTString()};path=/${path || ""};domain=${domain || location.hostname}`;};//删除某一个cookie的值
const delCookie = (key, path, domain) => {var k = key, val = getCookie(k);if (val != null) document.cookie = `${k}=0;expires=${new Date(0).toGMTString()};path=/${path || ""};domain=${domain || location.hostname}`;};//删除所有cookie的值
const delAllCookies = (path, domain) => {var ks = document.cookie.match(/[^ =;]+(?==)/g);if (ks) {for (var i = ks.length; i--;) (k = ks[i], document.cookie = `${k}=0;expires=${new Date(0).toGMTString()};path=/${path || ""};domain=${domain || location.hostname}`);}};//获取某一个url参数的值
const getUrlParam = a => (a = location.search.substr(1).match(new RegExp(`(^|&)${a}=([^&]*)(&|$)`)),a?a[2]:null);//获取所有url参数的值
const getUrlParams = url => {var reg = /([^=&s]+)[=s]*([^&s]*)/g, ls = url || location.search.substr(1), obj = {};while (reg.exec(ls)) obj[RegExp.$1] = decodeURIComponent(RegExp.$2);return obj;};

扩展阅读cookie常规实用方法合集(ES5)_你挚爱的强哥❤给你发来1条消息❤-CSDN博客var cookie = { getAll: function() { var arr = unescape(document.cookie).split("; "), o = {}; for (var i = 0, len = arr.length; i < len; i++) { var a = arr[i], index = a.https://s-z-q.blog.csdn.net/article/details/109088452

更多相关: