Reputation: 21
I am trying to do a simple IF statement to check if a specific Cookie exists: I'm not looking to over complicate anything just something simple like
if (document.cookie.name("a") == -1 {
console.log("false");
else {
console.log("true");
}
What is this syntax for this?
Upvotes: 2
Views: 6677
Reputation: 14199
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
;
}
}
Upvotes: 0
Reputation: 48
first:
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.
Upvotes: 2
Reputation: 33
Maybe this can help (w3schools documentation about javascript cookies) :
https://www.w3schools.com/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 "";
}
Upvotes: 1