按名称查找cookie然后使用javascript返回包含值的cookie(无jquery)

时间:2015-06-26 13:17:27

标签: javascript cookies

是否有一种懒惰的方式从document.cookie获取cookie?

如果是document.cookie,例如

  

abc_tracker = abc_visit_time%3D1435256807463%7Cabc_campaign_id%3D0%7Cabc_adgroup_id%3D0%7Cabc_content_id%3D0%7Cabc_medium%3Dreferral%7Cabc_source%3Dblog.example.com%7Cabc_campaign%3Dnone%7Cabc_adgroup%3Dnone%7Cabc_content%3Dnone%7Cabc_term%3Dnone%7Cabc_match %3Dnone%7Cabc_keyword%3Dnone%7Cabc_ref_keyword%3Dbm9uZQ%3D%3D%7Cabc_url%3DaHR0cDovL3d3dy5nb3dheS5jb20vP19nYT0xLjM4NTgyNjkxLjEyMTg5NTk2Mi4xNDM1MjQ5OTU2%7Cabc_ref_url%3DaHR0cDovL2Jsb2cuZ293YXkuY29tL2dsb2JldHJvdHRpbmcvP19nYT0xLjM4NTgyNjkxLjEyMTg5NTk2Mi4xNDM1MjQ5OTU2;   viewedOuibounceModal = TRUE; LAST_SLIDEIN_VIEW = 1435262685800;   LAST_SLIDEIN_TYPE = CHAT;   C_M = vst_channel%3Dundefined%7Cvst_keyword%3Dundefined%7Cvst_referringDomain%3Dundefined%7Cvst_campaign%3Dundefined;   __atuvc = 11%7C25; __atuvs = 558d4a4029c67edc001; bloglanding = FALSE; vst_tracker = ID%3D1435322882823%7Cvid%3D1435256807463%7Cmedium%3Ddirect%7Centry_page_url%3Dhttp%253A%252F%252Fwww.example.com%252F;   __utma = 148710120.217599539.1435256807.1435262252.1435322883.3; __utmb = 148710120.18.10.1435322883; __utmc = 148710120; __utmz = 148710120.1435256807.1.1.utmcsr = blog.example.com | utmccn =(引荐)| utmcmd =转诊| utmcct = /壮士/;   __utmv = 148710120 | 1 = VTIME = 1435256807463 = 1。 abc_page_count = 7; s_cc = TRUE; s_fid = 0B06C0537063F838-34C8F3D8F41ABCC8;   s_sq =%5B%5BB%5D%5D; _ga = GA1.2.121895962.1435249956;   __ar_v4 = 6UZ4UQZOCVE2RJGEKNO2AE%3A20150625%3A2%7CLDQ27DO6EFHARNHUHZLKF3%3A20150625%3A41%7CRYLYAX2L7NBGHDJQDTJYYL%3A20150625%3A41%7CDYK2HT5L5FGJNJFVXXPM4K%3A20150625%3A38%7CVIWWR64QNBEITBPWIV5TWP%3A20150625%3A1

我想说我想找到_ga cookie。阅读上面的cookie(靠近底部),整个事情是_ga=GA1.2.121895962.1435249956

仅使用vanilla Javascript,检索此内容的最简单方法是什么?

我在尝试使用匹配的兔子洞里走了下来:

var bla = document.cookie.match(/_ga/) // returns the matched string.
bla.input // returns the whole thing.

根据输入" _ga",返回以下值的简单方法是什么:_ga=GA1.2.121895962.1435249956

2 个答案:

答案 0 :(得分:2)

首先,设置功能

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

然后你只需要阅读并设置它。

//Setting
createCookie('_ga','9saua9s8d89w',7);
//Reading
var x = readCookie('_ga')
if (x) {
    //[do something with x]
}

修改 通过REGEXP

function readCookie(cookieName) {
 var re = new RegExp('[; ]'+cookieName+'=([^\\s;]*)');
 var sMatch = (' '+document.cookie).match(re);
 if (cookieName && sMatch) return unescape(sMatch[1]);
 return '';
}

然后

var x = readCookie('_ga');
if (x) {
    //[do something with x]
}

或者,只是REGEXP代码

var cookie = "_ga"
var re = new RegExp('[; ]'+cookie+'=([^\\s;]*)');
var cookieVal = unescape((' '+document.cookie).match(re)[1]);

console.log(cookieVal); //GA1.2.116321536.1432242890

答案 1 :(得分:1)

尝试以下方法:

var _ga = document.cookie.split(';').map(function(x) {
  return x.trim().split(/(=)/);
}).reduce(function(a, b) {
  a[b[0]] = a[b[0]] ? a[b[0]] + ', ' + b.slice(2).join('') :
    b.slice(2).join('');
  return a;
}, {})["_ga"]; // <--- cookie you are looking for.

console.log(_ga);

Here您可以找到更多相关信息。