0

Is there a lazy way to get a cookie from document.cookie?

If document.cookie is e.g.

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=(referral)|utmcmd=referral|utmcct=/globetrotting/; __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

Let's say I want to find the _ga cookie. Reading the cookie above (near the bottom) it's the whole thing is _ga=GA1.2.121895962.1435249956

Using vanilla Javascript only, what is the simplest way to retrieve this?

I went down a rabbit hole of trying to use match:

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

Based on input "_ga", What's a short simple way to get the following value returned: _ga=GA1.2.121895962.1435249956

Doug Fir
  • 19,971
  • 47
  • 169
  • 299

2 Answers2

2

First, you set the functions

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);
}

Then you just need to read and set it.

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

EDIT Via REGEXP

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

Then

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

OR, just the REGEXP code

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

console.log(cookieVal); //GA1.2.116321536.1432242890
Filipe Merker
  • 2,428
  • 1
  • 25
  • 41
1

Try the following:

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 you can find more info on that.

DavidDomain
  • 14,976
  • 4
  • 42
  • 50