3

我想在我的应用程序中删除一些 cookie。它们都是在应用程序本身中创建的。

在我的例子中,所有带有特殊字符串的 cookie 都应该被销毁。

目前我有以下代码来取消设置单个cookie:

var expires = new Date();
expires.setTime(expires.getTime() - 100);
document.cookie = name + '=' + value + '; expires=' + expires.toUTCString() + '; path=' + path + '; domain=' + domain;

我的 cookie 名称都是这样的:cookiename_identifier 和所有带有 cookiename_ 的都应该被删除。

4

4 回答 4

3

你可以这样做:

// Get an array of cookies
var arrSplit = document.cookie.split(";");

for(var i = 0; i < arrSplit.length; i++)
{
    var cookie = arrSplit[i].trim();
    var cookieName = cookie.split("=")[0];

    // If the prefix of the cookie's name matches the one specified, remove it
    if(cookieName.indexOf("cookiename_") === 0) {

        // Remove the cookie
        document.cookie = cookieName + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
}
于 2013-01-04T17:08:18.513 回答
2
// Get an array of all cookie names (the regex matches what we don't want)
var cookieNames = document.cookie.split(/=[^;]*(?:;\s*|$)/);

// Remove any that match the pattern
for (var i = 0; i < cookieNames.length; i++) {
    if (/^cookiename_/.test(cookieNames[i])) {
        document.cookie = cookieNames[i] + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=' + path;
    }
}
于 2013-01-04T17:07:07.937 回答
0

这对我来说非常有效。

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    } else 
        var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}


function eraseCookie(name) {
    createCookie(name,"",-1);
}

var cookieNames = document.cookie.split(/=[^;]*(?:;\s*|$)/);
for (var i = 0; i < cookieNames.length; i++) {
    if (cookieNames[i].includes(pattern)) {
        eraseCookie(cookieNames[i]);
    }
}

函数eraseCookiecreateCookie取自这里https://www.quirksmode.org/js/cookies.html。希望这可以帮助

于 2019-09-05T10:16:20.117 回答
0
    document.cookie.split(";").forEach(function(cookie) {

        var cookieName = cookie.trim().split("=")[0];

        // If the prefix of the cookie's name matches the one specified, remove it
        if (cookieName.indexOf("cookiename_") === 0) {

            // Remove the cookie
            document.cookie = cookieName + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
        }
    });
于 2021-05-27T04:10:17.023 回答