Javascript 如何检查cookie是否存在?
检查cookie是否存在的好方法是什么 条件: 如果Javascript 如何检查cookie是否存在?,javascript,html,cookies,Javascript,Html,Cookies,检查cookie是否存在的好方法是什么 条件: 如果 cookie1=;cookie1=345534; //or cookie1=345534;cookie1=; //or cookie1=345534; cookie=; //or <blank> 如果 cookie1=;cookie1=345534; //or cookie1=345534;cookie1=; //or cookie1=345534; cookie=; //or <blank> cookie=;
cookie1=;cookie1=345534;
//or
cookie1=345534;cookie1=;
//or
cookie1=345534;
cookie=;
//or
<blank>
如果
cookie1=;cookie1=345534;
//or
cookie1=345534;cookie1=;
//or
cookie1=345534;
cookie=;
//or
<blank>
cookie=;
//或
您可以使用所需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,那么可以使用 获取特定cookie的值的操作如下:
$.cookie('MyCookie'); // Returns the cookie value
我制作了一个替代的非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=');
如果cookie不存在,它将返回-1
p、 它的唯一缺点是(如评论中所述),如果有cookie设置了这样的名称,它就会出错:any\u prefix\u cookie\u name
()regexObject.(String)大于String.(RegExp)
描述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);
测试
函数cookieExists(输入){return/^(.*)?\s*cookie1\s*=/.test(输入);}
函数cookieExistsAndNotBlank(输入){return/^(.*)?\s*cookie1\s*=\s*[^;]/.test(输入);}
var testCases=['cookie1=;cookie1=345534;','cookie1=345534;cookie1=;','cookie1=345534;','cookie1=345534;','cookie123=345534;','cookie123=345534;','';
表(testCases.map(函数{return{'teststring':s,'cookieExists':cookieExists,'cookieexistsandbontblank':cookieexistsandbontblank}});
尝试了@jac函数,遇到了一些麻烦,下面是我如何编辑他的函数。注意!
选择的答案包含一个bug
如果您有多个cookie(很可能是…),并且您正在检索的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, '');
}
您只需使用document.cookie.split而不是cookie变量
var cookie='cookie1=s;cookie1=;cookie2=测试';
var cookies=cookie.split(“;”);
cookies.forEach(函数(c){
if(c.match(/cookie1=.+/))
console.log(true);
});
对于任何使用Node的人,我发现了一个使用ES6导入和cookie
模块的简单而好的解决方案
首先安装cookie模块(并另存为依赖项):
然后导入并使用:
import cookie from 'cookie';
let parsed = cookie.parse(document.cookie);
if('cookie1' in parsed)
console.log(parsed.cookie1);
请改用此方法:
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
}
}
这是一个老问题,但我使用的方法是
function getCookie(name) {
var match = document.cookie.match(RegExp('(?:^|;\\s*)' + name + '=([^;]*)'));
return match ? match[1] : null;
}
当cookie不存在或不包含请求的名称时,将返回null
。否则,将返回(请求名称的)值 cookie不应该没有值就存在——因为,公平地说,这有什么意义<代码>//************************************************************************存在cookie\u
/// ************************************************ 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
///全局入口点,导出到全局命名空间
///
///cookie_存在(名称);
///
///
///确定是否存在名为的cookie
///
///
///包含要测试的cookie名称的字符串
//存在
///
///
///如果cookie存在,则为true;否则,错误
///
///
///如果(cookie_存在(名称));
/// {
/////对现有cookie执行某些操作
/// }
///否则
/// {
/////cookies不存在,请执行其他操作
/// }
函数cookie_存在(名称)
{
var=false;
if(document.cookie)
{
如果(document.cookie.length>0)
{
//修剪名称
如果((name=name.replace(/^\s*/,“”)。长度>0))
{
var cookies=document.cookie.split(“;”);
变量名称,其中值等于名称+“=”;
对于(变量i=0;(i function getCookie(name) {
let matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
}
要获取cookie对象,只需调用getCookie()
要检查cookie是否存在,请执行以下操作:
if (!getcookie('myCookie')) {
console.log('myCookie does not exist.');
} else {
console.log('myCookie value is ' + getcookie('myCookie'));
}
或者只使用三元运算符。这里有几个很好的答案。然而,我更喜欢[1]不使用正则表达式,[2]使用易于阅读的逻辑,[3]使用一个短函数,如果名称是另一个cookie名称的子字符串,[4]不会返回true。最后,[5]我们不能对每个循环使用一个,因为返回不会破坏它
function cookieExists(name) {
var cks = document.cookie.split(';');
for(i = 0; i < cks.length; i++)
if (cks[i].split('=')[0].trim() == name) return true;
}
函数cookieExists(名称){
var cks=document.cookie.split(“;”);
对于(i=0;i
函数hasCookie(cookieName){
返回document.cookie.split(“;”)
.map(entry=>entry.split('='))
.some([name,value])=>(name.trim()==cookieName)和&!!value);
}
注意:如果cookie为空,作者希望函数返回false,即cookie=代码>这是通过&!!值
条件。如果你认为一个空的cookie仍然是一个现存的cookie,就删除它。
var cookie='cookie1=s;cookie1=;cookie2=测试';
var cookies=cookie.split(“;”);
cookies.forEach(函数(c){
if(c.match(/cookie1=.+/))
console.log(true);
});
请注意,如果cookie是安全的,则无法使用document.cookie在客户端检查其存在
function cookieExists(name) {
var cks = document.cookie.split(';');
for(i = 0; i < cks.length; i++)
if (cks[i].split('=')[0].trim() == name) return true;
}
function getCookie(cookiename) {
if (typeof(cookiename) == "string" && cookiename != "") {
const cookies = document.cookie.split(";");
for (i = 0; i < cookies.length; i++) {
if (cookies[i].trim().startsWith(cookiename)) {
return cookies[i].split("=")[1];
}
}
}
return null;
}