function to get a cookie

Hi guys,

I have the following function that gets a cookie. But I am having a hard time to understand the following code.
Can anybody explain this line by line?
if I call the function as follow
getCookie("Izzy")
what would happen to the code?

I don't understand from the beginning. why does name store cname + "=", not just cname?
function getCookie(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

Open in new window

IzzyTwinklyAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
function getCookie(cname) {
    // THIS IS WHAT WE ARE LOOKING FOR. 
    // BECAUSE COOKIES ARE IN THE FORM
    // cookie=value
    // AND WE ARE ONLY INTERESTED IN THE VALUE
    // WE ADD AN '=' TO THE  cookie NAME SO WE ARE
    // IN EFFECT LOOKING FOR
    // cookie=
    // THIS MEANS IN THE CODE BELOW WHEN WE STRIP
    // OUT THE NAME TO GET THE VALUE WE DON'T
    // HAVE TO WORRY ABOUT THE '='
    var name = cname + "=";
    // CREATE AN ARRAY FROM THE COOKIE STRING 
    // USING THE ';' AS A DELIMITER
    var ca = document.cookie.split(';');

    // LOOP THROUGH THE RESULTING ARRAY
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        // IGNORE ANY WHITESPACE FROM THE START
        // OF THE STRING BY ADVANCING A VAR (c)
        // THROUGH THE ARRAY AND CHECKING FOR
        // BLANK CHARS
        while (c.charAt(0)==' ') c = c.substring(1);
        // IF THE COOKIE WE ARE LOOKING FOR IS FOUND
        // AT THE START OF THE STRING 
        if (c.indexOf(name) == 0) {
            // RETURN THE VALUE FOUND IN THE STRING
            // STARTING AT THE LENGTH OF THE NAME
            // AND INCLUDING EVERYTHING AFTER THAT
            return c.substring(name.length, c.length);
        }
    }

    // NOT FOUND - RETURN THE EMPTY STRING
    return "";
}

Open in new window

More information here (http://www.w3schools.com/js/js_cookies.asp) - the source of the above code - also has an explanation on how it works.

// A SLIGHTLY MORE COMPACT FUNCTION
function getCookie(name) {
  // PREFIX THE COOKIE WITH "; " SO THAT THE 
  // split FUNCTION WORKS
  var value = "; " + document.cookie;
  // SPLIT THE STRING INTO 2 USING THE 
  // COOKIE NAME AND THE ABOVE PREFIX
  // "; " AS A DELIMITER. split DOES NOT INCLUDE
  // THE DELIMITER SO NOW WE HAVE A 2 ELEMENT
  // ARRAY WITH AN EMPTY ELEMENT AT THE START 
  // FOLLOWED BY A STRING THAT STARTS WITH
  // THE VALUE WE ARE LOOKING FOR. IF THE VALUE
  // DOES NOT EXIST THERE WILL ONLY BE 1 
  // ELEMENT IN THE ARRAY
  var parts = value.split("; " + name + "=");
  // IF THERE ARE 2 ELEMENTS IN THE ARRAY WE HAVE A MATCH
  // IN WHICH CASE 
  //    pop THE LAST VALUE WHICH IS THE ONE WITH THE VALUE
  // WE ARE LOOKING FOR (THE FIRST WAS A BLANK STRING)
  // split THE STRING ON ';' WHICH SEPARATES OUR VALUE FROM THE
  // REST OF THE COOKIE VALUES THAT MIGHT FOLLOW
  // shift - TAKE THE FIRST ELEMENT FROM THE NEW ARRAY 
  // AND RETURN IT. 
  if (parts.length == 2) return parts.pop().split(";").shift();
}

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Dave BaldwinFixer of ProblemsCommented:
Julian's explanation is good.  If you print 'document.cookie' to the screen, it will display a list of the cookies for the site in the form of 'name=value' separated by ';'.  Something like this:

name=value; name2=value2; name3=value3

This simple page will show you all the contents of 'document.cookie' on your site.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>document.cookie</title>
</head>
<body>
<h1>document.cookie</h1>
<script type="text/javascript">
<!--
var ca = document.cookie;
document.write(ca);
// -->
</script>
</body>
</html>

Open in new window

Prakash SamariyaIT ProfessionalCommented:
Simple explanation!
Cookie is a Key-Value paired collection to stores the site/page related information at the client computer to use within the page or while making the request!  

I don't understand from the beginning. why does name store cname + "=", not just cname?
As it is a collection, if we need a particular value how could we identify that? That's why it is added like Key-Value paired separated by semicolon(;) for e.g. cookieName1=value1;cookieName2=value2;cname=cvalue;  etc.

what would happen to the code?
In your function
getCookie("Izzy")
it asks to get the value of key "lzzy"!  In cookies it is stored as : lzzy=somevalue;
and it returns back it's value like "somevalue"
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

IzzyTwinklyAuthor Commented:
Thanks guys!
Please correct me if I am wrong.

so if I have a cookie like "name1=value1; name2=value2; cname=cvalue",
ca[0] contains "name1=value1"
ca[1] contains "name2=value2"
ca[2] contains "cname=cvalue"

when we loop through with ca
var c= ca[0]; // in here c will contain "name1=value1"

and it has while loop chekcing c.charAt(0)==' '. However, there is no ' ' in "name1=value1".
so c.substing(1) wouldn't be executed.
"name1=value1".indexOf("cname=")=0 is not true, so c.substring(name.length, c.length) wouldn't be executed.

The same process will be applied for ca[1], "name2=value2".

Now, for ca[2], "cname=cvalue",
c = "cname=cvalue"
again while(c.charAt(0)=' ') is false, c=c.substring(1) wouldn't be executed.
However, "cname=cvalue".indexOf("cname=") ==0 is true,
"cname=cvalue".substring(6, 12) will be returned, which is 'cvalue'.

Now I understand it, but I am wondering,
why would we need
while(c.charAt(0)==' ')
   c=c.substring(1);
?
Prakash SamariyaIT ProfessionalCommented:
why would we need
while(c.charAt(0)==' ')
   c=c.substring(1);
?
It is general rule in code key/name should not contains special chars like (space); that is the reason, if it is added extra prefixed white space, we ignore it and starts from second char

like " cname=value1", it will consider "cname=value1"

Hope you understand now! :)
Julian HansenCommented:
Refer lines 20-24 of the first code listing in my first post
        // IGNORE ANY WHITESPACE FROM THE START
        // OF THE STRING BY ADVANCING A VAR (c)
        // THROUGH THE ARRAY AND CHECKING FOR
        // BLANK CHARS
        while (c.charAt(0)==' ') c = c.substring(1)

Open in new window

The code makes sure there is no white space leading up to the start of the name so an accurate comparison of the key can be made. There should not be any WS there but it is a safety net in case.
The javascript trim() function could have been used as well
var c = ca[i].trim();

Open in new window

IzzyTwinklyAuthor Commented:
Thanks everybody including Dave.
Now I understand the code!!!
Julian HansenCommented:
You are welcome.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.