正则简单操作cookie、url search

时间:2022-12-27 15:48:26

正则操作cookie、url

  • getCookie
function getCookie(key) {
var cookies = window.document.cookie,
reg = new RegExp('\\S*' + key + '=[^;]*', 'gi');
var result = cookies.match(reg);
return result && result[0].substr(0, key.length) === key ? result[0].substr(key.length + 1) : false;
}
  • setCookie
function setCookie(key, value, expires) { // expires为天数
var date = new Date();
date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1000);
document.cookie = key + '=' + value + ';expires=' + date;
}
  • getQuery
function getQuery(key) {
var search = window.location.search,
reg = new RegExp('[^&]*' + key + '=[^&]*', 'gi');
var result = search.substr(1).match(reg);
return result && result[0].substr(0, key.length) === key ? window.decodeURIComponent(result[0].substr(key.length + 1)) : false;
}
  • getUrl
function getUrl() {
var search = window.location.search,
reg = /[^=]+/g;
var deal = search.substr(1).split('&'),
result = {};
deal.forEach(function(item) {
var temp = item.match(reg);
temp && (result[temp[0]] = decodeURIComponent(temp[1]));
});
return result;
}