IT & Programming

Reading cookie with JavaScript

As compared to PHP, it is a but complex to read a cookie with JavaScript. Below is custom made JavaScript cookie function that can read a cookie easily. All you have to do is to pass 1 parameter. name of the cookie.

Function

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;
}
Calling T

Calling The Function

readCookie('country');

Output

null or cookie value

Leave A comment

Email address is optional and will not be published. Only add email address if you want a reply from blog author.
Please fill required fields marked with *