Javascript 检查 cookie 如果 cookie 存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5968196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
check cookie if cookie exists
提问by confuzzled
What's a good way to check if a cookie exist?
检查 cookie 是否存在的好方法是什么?
Conditions:
状况:
Cookie exists if
Cookie 存在,如果
cookie1=;cookie1=345534;
//or
cookie1=345534;cookie1=;
//or
cookie1=345534;
Cookie doesn't exist if
如果 Cookie 不存在
cookie=;
//or
<blank>
回答by jac
You can call the function getCookie with the name of the cookie you want, then check to see if it is = null.
您可以使用您想要的 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
}
}
回答by hegemon
I have crafted an alternative non-jQuery version:
我制作了一个替代的非 jQuery 版本:
document.cookie.match(/^(.*;)?\s*MyCookie\s*=\s*[^;]+(.*)?$/)
It only tests for cookie existence. A more complicated version can also return cookie value:
它只测试 cookie 的存在。更复杂的版本也可以返回 cookie 值:
value_or_null = (document.cookie.match(/^(?:.*;)?\s*MyCookie\s*=\s*([^;]+)(?:.*)?$/)||[,null])[1]
Put your cookie name in in place of MyCookie
.
将您的 cookie 名称替换为MyCookie
.
回答by HackToHell
document.cookie.indexOf('cookie_name=');
It will return -1
if that cookie does not exist.
-1
如果该 cookie 不存在,它将返回。
p.s. Only drawback of it is (as mentioned in comments) that it will mistake if there is cookie set with such name: any_prefix_cookie_name
ps 唯一的缺点是(如评论中所述)如果设置了具有此类名称的 cookie,则会出错: any_prefix_cookie_name
(Source)
(来源)
回答by Pikkio
ATTENTION! the chosen answer contains a bug (Jac's answer).
注意力!所选答案包含错误(Jac 的答案)。
if you have more than one cookie (very likely..) and the cookie you are retrieving is the first on the list, it doesn't set the variable "end" and therefore it will return the entire string of characters following the "cookieName=" within the document.cookie string!
如果您有多个 cookie(很可能..)并且您正在检索的 cookie 是列表中的第一个,它不会设置变量“end”,因此它将返回“cookieName”之后的整个字符串=" 在 document.cookie 字符串中!
here is a revised version of that function:
这是该功能的修订版:
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, '');
}
回答by HeWhoProtects
If you're using jQuery, you can use the jquery.cookie plugin.
如果您使用 jQuery,则可以使用jquery.cookie 插件。
Getting the value for a particular cookie is done as follows:
获取特定 cookie 的值按如下方式完成:
$.cookie('MyCookie'); // Returns the cookie value
回答by hajamie
regexObject.test( String ) is fasterthan string.match( RegExp ).
正则对象。test( String )比 string快。匹配(正则表达式)。
The MDN sitedescribes the format for document.cookie, and has an example regex to grab a cookie (document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");
). Based on that, I'd go for this:
所述MDN站点描述的document.cookie的格式,并且具有正则表达式示例抓住一个cookie( document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");
)。基于此,我会这样做:
/^(.*;)?\s*cookie1\s*=/.test(document.cookie);
The question seems to ask for a solution which returns false when the cookie is set, but empty. In that case:
该问题似乎要求一种解决方案,该解决方案在设置 cookie 时返回 false,但为空。在这种情况下:
/^(.*;)?\s*cookie1\s*=\s*[^;]/.test(document.cookie);
Tests
测试
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)}}));
回答by Dustin Halstead
This is an old question, but here's the approach I use ...
这是一个老问题,但这是我使用的方法......
function getCookie(name) {
var match = document.cookie.match(RegExp('(?:^|;\s*)' + name + '=([^;]*)')); return match ? match[1] : null;
}
This returns null
either when the cookie doesn't exist, or when it doesn't contain the requested name.
Otherwise, the value (of the requested name) is returned.
这将null
在 cookie 不存在或不包含请求的名称时返回。
否则,返回(请求名称的)值。
A cookie should never exist without a value -- because, in all fairness, what's the point of that?
If it's no longer needed, it's best to just get rid of it all together.
没有值的 cookie 永远不应该存在——因为,平心而论,那有什么意义呢?
如果不再需要它,最好一起摆脱它。
function deleteCookie(name) {
document.cookie = name +"=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}
回答by Ashish
Using Javascript:
使用 JavaScript:
function getCookie(name) {
let matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\/\+^])/g, '\') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
}
回答by Matheus
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;
}
Tried @jac function, got some trouble, here's how I edited his function.
尝试了@jac 函数,遇到了一些麻烦,这是我编辑他的函数的方法。
回答by KFish
instead of the cookie variable you would just use document.cookie.split...
而不是 cookie 变量,您只需使用 document.cookie.split ...
var cookie = 'cookie1=s; cookie1=; cookie2=test';
var cookies = cookie.split('; ');
cookies.forEach(function(c){
if(c.match(/cookie1=.+/))
console.log(true);
});