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

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

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

试试这个。

        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) 并且它应该 return 一个包含 cookie 的字符串。然后只需对 returned 值使用 split 即可获取数组。 希望这对你有用。

完全实用的方法:

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'));