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 に答える