Javascript function to Read Cookie by Name

Most of the times we come across situations where we need to read cookies using javascript. Javascript has a built in property for document object called as cookie which is useful for getting cookies. But problem with this property is it actually returns all the cookies as string! so you will end up getting values like “cookie1=val1; cookie2=val2; cookie3=val3”

So to take care of splitting the string and getting value for only required cookie I tend to use small function which basically expects name of a cookie and returns corresponding value for the same.

function getCookie(name) {
        var re = new RegExp(name + "=([^;]+)");
        var value = re.exec(document.cookie);
        return (value != null) ? unescape(value[1]) : null;
    }

Just pass name of cookie to the function and it will return you value of the cookie. In case the cookie is not present it will return you null.

So to read value of any cookie you will use following syntax ( after adding above function in your JS code )

var cookie1Val = getCookie("cookie1");
console.log(cookie1Val); // Log cookie value to console just for demonstration purpose.

Please note:
HTTP ONLY cookies can not be read using JAVASCRIPT. If you are trying to access such cookie by document.cookie it won’t work.

Add a Comment

Your email address will not be published. Required fields are marked *