使用正则表达式删除或删除Javascript Cookie(正则表达式)

问题描述 投票:-2回答:2

Cookies to remove or delete with regex

The Cookie is Not Returned in the normal document.cookie function

这是一个我想删除或删除最后5个cookie的网站,以“搜索”开头,用javascript Regex(正则表达式)我该怎么做

Cookie在常规document.cookie函数中未返回

我尝试了很多技巧和代码而没有工作......请帮忙

javascript regex cookies session-cookies
2个回答
1
投票

你可以试试这个:

    function deleteCookie(name) {
        document.cookie = name + "=; expires=" + (new Date(0)).toUTCString() + ";";
    };
    function findCookies(name) {
        var r=[];
        document.cookie.replace(new RegExp("("+name + "[^= ]*) *(?=\=)", "g"), function(a, b, ix){if(/[ ;]/.test(document.cookie.substr(ix-1, 1))) r.push(a.trim());})
        return r;
    };

用法:

findCookies("search").forEach(function(fullName){deleteCookie(fullName);});

或者使用它,如果你只需要其中的5个(从最后一个):

findCookies("search").slice(-5).forEach(function(fullName){deleteCookie(fullName);});

1
投票
//to get all the cookies 
var cookiesArray = document.cookie.split(";"); <br>
//loop through the array and check if the cookie name is what we want
for(var i = 0; i < cookiesArray.length; i++)
{
    //remove if any extra space
    var cookie = cookiesArray[i].trim();
    //to get the cookie name
    var cookieName = cookie.split("=")[0];

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

        // Remove the cookie
        document.cookie = cookieName + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;";
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.