检查cookie是否存在的好方法是什么?
条件:
Cookie存在,如果
cookie1=;cookie1=345534;
//or
cookie1=345534;cookie1=;
//or
cookie1=345534;
如果不存在Cookie,
cookie=;
//or
<blank>
Answers:
您可以使用所需Cookie的名称调用函数getCookie,然后检查其是否为null。
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
}
}
我制作了一个替代的非jQuery版本:
document.cookie.match(/^(.*;)?\s*MyCookie\s*=\s*[^;]+(.*)?$/)
它仅测试cookie的存在。更复杂的版本也可以返回cookie值:
value_or_null = (document.cookie.match(/^(?:.*;)?\s*MyCookie\s*=\s*([^;]+)(?:.*)?$/)||[,null])[1]
将您的Cookie名称替换为MyCookie
。
document.cookie.indexOf('cookie_name=');
-1
如果该cookie不存在,它将返回。
ps它的唯一缺点是(如注释中所述),如果设置了具有以下名称的cookie,它将出错: any_prefix_cookie_name
(来源)
-1
ifcookie_name_whatever
设置(即使未设置cookie_name)。另一个答案中的正则表达式版本可以解决该问题。
注意!选择的答案包含一个错误(Jac的答案)。
如果您有多个cookie(很有可能..),并且要检索的cookie是列表中的第一个cookie,则不会设置变量“ end”,因此它将返回“ cookieName”之后的整个字符串在document.cookie字符串中=“ =”!
这是该功能的修订版:
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, '');
}
如果您使用的是jQuery,则可以使用jquery.cookie插件。
获取特定Cookie的值的操作如下:
$.cookie('MyCookie'); // Returns the cookie value
regexObject。test(String)比string快。匹配(RegExp)。
所述MDN站点描述的document.cookie的格式,并且具有正则表达式示例抓住一个cookie( document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");
)。基于此,我会这样做:
/^(.*;)?\s*cookie1\s*=/.test(document.cookie);
问题似乎是要寻求一种解决方案,该解决方案在设置cookie时返回false,但为空。在这种情况下:
/^(.*;)?\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)}}));
这是一个老问题,但这是我使用的方法...
function getCookie(name) {
var match = document.cookie.match(RegExp('(?:^|;\\s*)' + name + '=([^;]*)')); return match ? match[1] : null;
}
null
当cookie不存在或不包含请求的名称时,将返回此值。
否则,返回(所请求名称的)值。
没有价值的cookie永远不应该存在-因为公平地说,这有什么意义?😄
如果不再需要它,则最好将其全部消除。
function deleteCookie(name) {
document.cookie = name +"=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}
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{
var oneCookie = dc.indexOf(';', begin);
if(oneCookie == -1){
var end = dc.length;
}else{
var end = oneCookie;
}
return dc.substring(begin, end).replace(prefix,'');
}
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
var fixed = dc.substring(begin, end).replace(prefix,'');
}
// return decodeURI(dc.substring(begin + prefix.length, end));
return fixed;
}
尝试了@jac函数,遇到了一些麻烦,这是我编辑他的函数的方式。
请改用此方法:
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
else return null;
}
function doSomething() {
var myCookie = getCookie("MyCookie");
if (myCookie == null) {
// do cookie doesn't exist stuff;
}
else {
// do cookie exists stuff
}
}
/// ************************************************ cookie_exists
/// global entry point, export to global namespace
/// <synopsis>
/// cookie_exists ( name );
///
/// <summary>
/// determines if a cookie with name exists
///
/// <param name="name">
/// string containing the name of the cookie to test for
// existence
///
/// <returns>
/// true, if the cookie exists; otherwise, false
///
/// <example>
/// if ( cookie_exists ( name ) );
/// {
/// // do something with the existing cookie
/// }
/// else
/// {
/// // cookies does not exist, do something else
/// }
function cookie_exists ( name )
{
var exists = false;
if ( document.cookie )
{
if ( document.cookie.length > 0 )
{
// trim name
if ( ( name = name.replace ( /^\s*/, "" ).length > 0 ) )
{
var cookies = document.cookie.split ( ";" );
var name_with_equal = name + "=";
for ( var i = 0; ( i < cookies.length ); i++ )
{
// trim cookie
var cookie = cookies [ i ].replace ( /^\s*/, "" );
if ( cookie.indexOf ( name_with_equal ) === 0 )
{
exists = true;
break;
}
}
}
}
}
return ( exists );
} // cookie_exists
function getcookie(name = '') {
let cookies = document.cookie;
let cookiestore = {};
cookies = cookies.split(";");
if (cookies[0] == "" && cookies[0][0] == undefined) {
return undefined;
}
cookies.forEach(function(cookie) {
cookie = cookie.split(/=(.+)/);
if (cookie[0].substr(0, 1) == ' ') {
cookie[0] = cookie[0].substr(1);
}
cookiestore[cookie[0]] = cookie[1];
});
return (name !== '' ? cookiestore[name] : cookiestore);
}
要获取Cookie的对象,只需调用 getCookie()
要检查cookie是否存在,请按照以下步骤进行操作:
if (!getcookie('myCookie')) {
console.log('myCookie does not exist.');
} else {
console.log('myCookie value is ' + getcookie('myCookie'));
}
或仅使用三元运算符。
unescape
已弃用,因此使用之间有什么区别decodeURIComponent
吗?