删除名称中包含特定字符串的所有cookie

时间:2013-01-04 16:25:56

标签: javascript cookies

我想在我的应用程序中删除一些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 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:2)

你可以这样做:

// 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";
    }
}

答案 2 :(得分: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。希望这会有所帮助

答案 3 :(得分:0)

// when people gets jail role, add following code:
db.set(`ja_${msg.guild.id}_${user}`, "yes") // or you can simply use boolean operator

// when guildMemberAdd event triggers check condition:
let condition = db.fech(`ja_${member.guild.id}_${member.user.id}`)

if(condition === "yes"){
    // write code to add "jail" role to the member
}
else{
    // your other code
}