2

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?

Jake...
  • 21
  • 1
  • 2

3 Answers3

2

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.

addictive
  • 48
  • 3
1

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 "";
}
Romain
  • 33
  • 9
  • 2
    Please add the essential relevant parts of the linked content to your answer; see [How do I write a good answer](https://stackoverflow.com/help/how-to-answer). – Frxstrem May 19 '17 at 10:34
0

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
    ;
  }
}
Hitmands
  • 13,491
  • 4
  • 34
  • 69