JavaScript check if a cookie exists via Name - Stack Overflow

I am trying to do a simple IF statement to check if a specific Cookie exists:I'm not looking to o

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
Add a ment  | 

3 Answers 3

Reset to default 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.

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

相关推荐

  • JavaScript check if a cookie exists via Name - Stack Overflow

    I am trying to do a simple IF statement to check if a specific Cookie exists:I'm not looking to o

    5小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信