I am trying to do a simple IF statement to check if a specific Cookie exists: I'm not looking to over plicate anything just something simple like
if (document.cookie.name("a") == -1 {
console.log("false");
else {
console.log("true");
}
What is this syntax for this?
I am trying to do a simple IF statement to check if a specific Cookie exists: I'm not looking to over plicate anything just something simple like
if (document.cookie.name("a") == -1 {
console.log("false");
else {
console.log("true");
}
What is this syntax for this?
Share Improve this question asked May 19, 2017 at 10:28 Jake...Jake... 211 silver badge2 bronze badges 1- Possible duplicate of check cookie if cookie exists – Sampath Wijesinghe Commented May 19, 2017 at 10:34
3 Answers
Reset to default 2first:
function getCookie(name) {
var cookies = '; ' + document.cookie;
var splitCookie = cookies.split('; ' + name + '=');
if (splitCookie.lenght == 2) return splitCookie.pop();
}
then you can use your if statement:
if (getCookie('a'))
console.log("false");
else
console.log("true");
should have work.
Maybe this can help (w3schools documentation about javascript cookies) :
https://www.w3schools./js/js_cookies.asp
At A Function to Get a Cookie
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}
this could help you:
class Cookies {
static exists(name) {
return name && !!Cookies.get(name);
}
static set(name, value, expires = Date.now() + 8.64e+7, path = '/') {
document.cookie = `${name}=${value};expires=${expires};path=${path};`;
}
static get(name = null) {
const cookies = decodeURIComponent(document.cookie)
.split(/;\s?/)
.map(c => {
let [name, value] = c.split(/\s?=\s?/);
return {name, value};
})
;
return name
? cookies.filter(c => c.name === name).pop() || null
: cookies
;
}
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745421164a4626968.html
评论列表(0条)