Link to home
Start Free TrialLog in
Avatar of IzzyTwinkly
IzzyTwinklyFlag for United States of America

asked on

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

ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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

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"
Avatar of IzzyTwinkly

ASKER

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);
?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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

Thanks everybody including Dave.
Now I understand the code!!!
You are welcome.