如何获取包含以word
开头的所有Cookie名称的数组?
答案 0 :(得分:3)
完全功能性方法:
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'));
答案 1 :(得分:0)
试试这个。
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来获取数组。 希望这对你有用。