2013-01-04 118 views
2

我想在我的應用程序中刪除一些cookie。它們都是在應用程序本身中創建的。刪除名稱中包含特定字符串的所有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_應予刪除。

+0

你能舉一個例子來什麼'document.cookie'(包含要擺脫幾個值)輸出? – inhan

回答

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

你可以做這樣的事情:

// 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"; 
    } 
} 
相關問題