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?

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Nice one, any reason why the condition is splitCookie.length == 2 and not just splitCookie.length?
Small typo in there at splitCookie.lenght
do you put the if statement inside the function, or outside the function?
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 "";
}

1 Comment

Please add the essential relevant parts of the linked content to your answer; see How do I write a good answer.
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
    ;
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.