learnerX
learnerX

Reputation: 1082

Analyzing JS code to grab a cookie at client-side

I'm new to JS, and I am analyzing a long program code. I cannot understanding this function, except that it is trying to grab a cookie from the client-side. Could anyone point out the functionality here?

function get_cookie(a) {
        var b = a + "=";
        var c = "";
        if (document.cookie.length > 0) {
             offset = document.cookie.indexOf(b);
             if (offset != -1) {
                 offset += b.length;
                 end = document.cookie.indexOf(";", offset);
                 if (end == -1) {
                     end = document.cookie.length;
                }
                c = unescape(document.cookie.substring(offset, end));
            }
        }
        return c;
    }

Upvotes: 1

Views: 121

Answers (1)

Raja Sekar
Raja Sekar

Reputation: 2130

function get_cookie(a) {
        var b = a + "="; // Getting argument a and assigning it to var b appending =
        var c = ""; // defining variable c  
        if (document.cookie.length > 0) {  //checking cookie length in browser
             offset = document.cookie.indexOf(b);  // checking b exists or not
             if (offset != -1) { // if b exists 
                 offset += b.length; // getting no of string and assigning it to offset
                 end = document.cookie.indexOf(";", offset); //checking if ';' is present
                 if (end == -1) { // if ';' is not there in cookie string, 
                     end = document.cookie.length; - // cookie is not set, SO assigning length to the variable end
                }
                c = unescape(document.cookie.substring(offset, end)); // assigning those values to c
            }
        }
        return c; // returning new cookie.
    }

Upvotes: 1

Related Questions