Friday, October 28, 2011

Easy way to read cookie and with out loop..

Assuming, reader know about what is cookie.
As of you know, document.cookie is java script key word and most of the times i use to write on OOP's.
let us code:

  1. var obj={};
  2. obj.c=document.cookie;
  3. //Define read cookie name:
    obj.cName = '__utmz';
  4. //split obj.c, this way:
    obj.c1 =obj.c.split(obj.cName+'=');
    // here am adding "=" to cookie name, because browser stores cookie and values as in format of string
    Ex: "TL=te:0; __utma=150635877.1168279805.1319048317.1319048317.1319822141.2; __utmb=150635877.3.10.1319822141; __utmc=150635877; __utmz=150635877.1319048317.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)"
  5. simple check an condition if obj.c1 > 1 then expected cookie exist other wise, dose not exist.
  6. if Exists:
    obj.data = obj.c1[1].split(';')[0]
  7. Finally obj.data is your cookie data.
In single line of code for reading cookie value is
function readcookie(cookiename){
var val = '';
try{
//if cookie present on the doc
              val = document.cookie.split(cookiename)[1].split('; ')[0].split('=')[1]
 }catch(e){
//cookie dose not present on the doc.
val = '';
}
return val;
}

var cookieVal = readcookie('cookiename');

Thank you.