如何检查Cookie是否存在?
条件:
如果Cookie存在,则为真
cookie1=;cookie1=345534;
//or
cookie1=345534;cookie1=;
//or
cookie1=345534;
如果满足以下条件,则Cookie不存在:
cookie=;
//or
<blank>
如何检查Cookie是否存在?
条件:
如果Cookie存在,则为真
cookie1=;cookie1=345534;
//or
cookie1=345534;cookie1=;
//or
cookie1=345534;
如果满足以下条件,则Cookie不存在:
cookie=;
//or
<blank>
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
// because unescape has been deprecated, replaced with decodeURI
//return unescape(dc.substring(begin + prefix.length, end));
return decodeURI(dc.substring(begin + prefix.length, end));
}
function doSomething() {
var myCookie = getCookie("MyCookie");
if (myCookie == null) {
// do cookie doesn't exist stuff;
}
else {
// do cookie exists stuff
}
}
document.cookie.match(/^(.*;)?\s*MyCookie\s*=\s*[^;]+(.*)?$/)
value_or_null = (document.cookie.match(/^(?:.*;)?\s*MyCookie\s*=\s*([^;]+)(?:.*)?$/)||[,null])[1]
MyCookie
。document.cookie.indexOf('cookie_name=');
如果该cookie不存在,它将返回-1
。
p.s. 它唯一的缺点是(如评论中所提到的),如果设置了名为any_prefix_cookie_name
的cookie,则会出现错误。
(来源)
cookie_name_whatever
(即使没有设置cookie_name),则示例返回除“-1”以外的某些结果。另一个答案中的正则表达式版本可以解决这个问题。 - hajamiedocument.cookie.indexOf('cookie_name=') == 0;
可以解决这个问题。只有当 cookie 以所提到的文本开头时才为真,否则为假。 - Lasse Jacobs这是一个老问题,但以下是我使用的方法...
function getCookie(name) {
var match = document.cookie.match(RegExp('(?:^|;\\s*)' + name + '=([^;]*)'));
return match ? match[1] : null;
}
当cookie不存在或不包含所请求的名称时,它返回null
。
否则,将返回请求名称的值。
一个cookie不应该存在但没有值--因为这样做毫无意义。
如果不再需要,最好彻底删除。
function deleteCookie(name) {
document.cookie = name +"=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}
return match && match[1];
进一步简化 getCookie
函数,因为当 match
不是“正”条件时,它将返回 null
。 - lbragile注意!所选答案包含错误(Jac's answer)。
如果您有多个cookie(很可能..),而且要检索的cookie是列表中的第一个,它将不会设置变量“end”,因此它将返回在document.cookie字符串中“cookieName =”后面的所有字符的字符串!
这是该函数的修订版本:
function getCookie( name ) {
var dc,
prefix,
begin,
end;
dc = document.cookie;
prefix = name + "=";
begin = dc.indexOf("; " + prefix);
end = dc.length; // default to end of the string
// found, and not in first position
if (begin !== -1) {
// exclude the "; "
begin += 2;
} else {
//see if cookie is in first position
begin = dc.indexOf(prefix);
// not found at all or found as a portion of another cookie name
if (begin === -1 || begin !== 0 ) return null;
}
// if we find a ";" somewhere after the prefix position then "end" is that position,
// otherwise it defaults to the end of the string
if (dc.indexOf(";", begin) !== -1) {
end = dc.indexOf(";", begin);
}
return decodeURI(dc.substring(begin + prefix.length, end) ).replace(/\"/g, '');
}
$.cookie('MyCookie'); // Returns the cookie value
document.cookie
在客户端检查它的存在性(所有答案都在使用此方法)。这种 cookie 只能在服务器端检查。regexObject.test(字符串)比string.match(正则表达式)更快速。
MDN网站描述了document.cookie的格式,并提供了一个抓取cookie的示例正则表达式(document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");
)。基于此,我会选择以下代码:
/^(.*;)?\s*cookie1\s*=/.test(document.cookie);
/^(.*;)?\s*cookie1\s*=\s*[^;]/.test(document.cookie);
测试
function cookieExists(input) {return /^(.*;)?\s*cookie1\s*=/.test(input);}
function cookieExistsAndNotBlank(input) {return /^(.*;)?\s*cookie1\s*=\s*[^;]/.test(input);}
var testCases = ['cookie1=;cookie1=345534;', 'cookie1=345534;cookie1=;', 'cookie1=345534;', ' cookie1 = 345534; ', 'cookie1=;', 'cookie123=345534;', 'cookie=345534;', ''];
console.table(testCases.map(function(s){return {'Test String': s, 'cookieExists': cookieExists(s), 'cookieExistsAndNotBlank': cookieExistsAndNotBlank(s)}}));
你可以使用 document.cookie.split... 代替 cookie 变量。
var cookie = 'cookie1=s; cookie1=; cookie2=test';
var cookies = cookie.split('; ');
cookies.forEach(function(c){
if(c.match(/cookie1=.+/))
console.log(true);
});
这里有几个不错的答案。然而,我更喜欢[1]不使用正则表达式,[2]使用易于阅读的逻辑,[3]拥有一个短函数,[4]如果名称是另一个cookie名称的子字符串,则不返回true。最后,[5]我们不能使用forEach循环,因为return语句无法中断它。
function cookieExists(name) {
var cks = document.cookie.split(';');
for(i = 0; i < cks.length; i++)
if (cks[i].split('=')[0].trim() == name) return true;
}
unescape
е·Із»Џиў«ејѓз”ЁпјЊй‚Јд№€дЅїз”ЁdecodeURIComponent
代替有什么区别吗? - the_nuts