admin管理员组

文章数量:1129704

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

Conditions:

Cookie exists if

cookie1=;cookie1=345534;
//or
cookie1=345534;cookie1=;
//or
cookie1=345534;

Cookie doesn't exist if

cookie=;
//or
<blank>

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

Conditions:

Cookie exists if

cookie1=;cookie1=345534;
//or
cookie1=345534;cookie1=;
//or
cookie1=345534;

Cookie doesn't exist if

cookie=;
//or
<blank>
Share Improve this question edited Nov 11, 2020 at 2:02 Edric 26.7k13 gold badges87 silver badges95 bronze badges asked May 11, 2011 at 17:28 confuzzledconfuzzled 1,4132 gold badges10 silver badges4 bronze badges
Add a comment  | 

24 Answers 24

Reset to default 166

You can call the function getCookie with the name of the cookie you want, then check to see if it is = null.

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
        end = dc.length;
        }
    }
    // because unescape has been deprecated, replaced with decodeURI
    //return unescape(dc.substring(begin + prefix.length, end));
    return decodeURI(dc.substring(begin + prefix.length, end));
} 

function doSomething() {
    var myCookie = getCookie("MyCookie");

    if (myCookie == null) {
        // do cookie doesn't exist stuff;
    }
    else {
        // do cookie exists stuff
    }
}

I have crafted an alternative non-jQuery version:

document.cookie.match(/^(.*;)?\s*MyCookie\s*=\s*[^;]+(.*)?$/)

It only tests for cookie existence. A more complicated version can also return cookie value:

value_or_null = (document.cookie.match(/^(?:.*;)?\s*MyCookie\s*=\s*([^;]+)(?:.*)?$/)||[,null])[1]

Put your cookie name in in place of MyCookie.

document.cookie.indexOf('cookie_name=');

It will return -1 if that cookie does not exist.

p.s. Only drawback of it is (as mentioned in comments) that it will mistake if there is cookie set with such name: any_prefix_cookie_name

(Source)

This is an old question, but here's the approach I use ...

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

This returns null either when the cookie doesn't exist, or when it doesn't contain the requested name.
Otherwise, the value (of the requested name) is returned.

A cookie should never exist without a value -- because, in all fairness, what's the point of that?

本文标签: javascriptHow do I check if a cookie existsStack Overflow