如何使用 JavaScript 获取所有以单词开头的 cookie

How to get all cookies starting with a word using JavaScript?

本文关键字:单词 开头 cookie 何使用 JavaScript 获取      更新时间:2023-09-26

如何获取一个包含所有以 word 开头的 cookie 名称的数组?

完全功能的方法:

document.cookie.split(';').filter(function(c) {
    return c.trim().indexOf('word') === 0;
}).map(function(c) {
    return c.trim();
});

附有解释:

//Get a list of all cookies as a semicolon+space-separated string
document.cookie.split(';')
//Filter determines if an element should remain in the array.  Here we check if a search string appears at the beginning of the string
.filter(function(c) {
    return c.trim().indexOf('word') === 0;
})
//Map applies a modifier to all elements in an array, here we trim spaces on both sides of the string
.map(function(c) {
    return c.trim();
});

ES6:

document.cookie.split(';')
    .filter(c => c.startsWith('word'));

试试这个。

        function getCookie(cname) {
            var name = cname + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) === ' ') c = c.substring(1);
                if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
            }
            return "";
        }

然后你应该能够使用 getCookie(name),它应该返回一个包含 cookie 的字符串。然后只需在返回值上使用 split 即可获取数组。希望这对你有用。