What's a good way to check if a cookie exist in JavaScript?

By: Varghese Chacko 1 year, 2 months ago

What's a good way to check if a cookie exist using Javascript? The cookie is available to Javascript via document.cookie So the easiest method is to write a function that checks with document.cookie and return

function getCookie(name) {
    var match = document.cookie.match(RegExp('(?:^|;\\s*)' + name + '=([^;]*)')); return match ? match[1] : null;

We can define this function in multiple ways. Another simple method would be: document.cookie.indexOf('cookie_name='); This one just checks dor the existance of the cookie, but it doesn't return the value like above function does.

Another implementation would be

function getCookie(name) {
    var value = "; " + document.cookie;
    var parts = value.split("; " + name + "=");
    if (parts.length == 2) return parts.pop().split(";").shift();
    else return null;

In short, its how we extract thedata from document.cookie