1. 程式人生 > >正則簡單操作cookie、url search

正則簡單操作cookie、url search

正則操作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);
    console.log(date)
    document.cookie = key + '=' + value + ';expires=' + date;
}
  • getQuery
function getQueryl(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;
}