Get cookie by name

前端 未结 30 1412
野的像风
野的像风 2020-11-22 03:58

I have a getter to get the value from a cookie.

Now I have 2 cookies by the name shares= and by the name obligations= .

I want to

相关标签:
30条回答
  • 2020-11-22 04:31
    function getCookie(name) {
        var pair = document.cookie.split('; ').find(x => x.startsWith(name+'='));
        if (pair)
           return pair.split('=')[1]
    }
    
    0 讨论(0)
  • 2020-11-22 04:32

    Use object.defineProperty

    With this, you can easily access cookies

    Object.defineProperty(window, "Cookies", {
        get: function() {
            return document.cookie.split(';').reduce(function(cookies, cookie) {
                cookies[cookie.split("=")[0]] = unescape(cookie.split("=")[1]);
                return cookies
            }, {});
        }
    });
    

    From now on you can just do:

    alert( Cookies.obligations );
    

    This will automatically update too, so if you change a cookie, the Cookies will change too.

    0 讨论(0)
  • 2020-11-22 04:34

    The methods in some of the other answers that use a regular expression do not cover all cases, particularly:

    1. When the cookie is the last cookie. In this case there will not be a semicolon after the cookie value.
    2. When another cookie name ends with the name being looked up. For example, you are looking for the cookie named "one", and there is a cookie named "done".
    3. When the cookie name includes characters that are not interpreted as themselves when used in a regular expression unless they are preceded by a backslash.

    The following method handles these cases:

    function getCookie(name) {
        function escape(s) { return s.replace(/([.*+?\^$(){}|\[\]\/\\])/g, '\\$1'); }
        var match = document.cookie.match(RegExp('(?:^|;\\s*)' + escape(name) + '=([^;]*)'));
        return match ? match[1] : null;
    }
    

    This will return null if the cookie is not found. It will return an empty string if the value of the cookie is empty.

    Notes:

    1. This function assumes cookie names are case sensitive.
    2. document.cookie - When this appears on the right-hand side of an assignment, it represents a string containing a semicolon-separated list of cookies, which in turn are name=value pairs. There appears to be a single space after each semicolon.
    3. String.prototype.match() - Returns null when no match is found. Returns an array when a match is found, and the element at index [1] is the value of the first matching group.

    Regular Expression Notes:

    1. (?:xxxx) - forms a non-matching group.
    2. ^ - matches the start of the string.
    3. | - separates alternative patterns for the group.
    4. ;\\s* - matches one semi-colon followed by zero or more whitespace characters.
    5. = - matches one equal sign.
    6. (xxxx) - forms a matching group.
    7. [^;]* - matches zero or more characters other than a semi-colon. This means it will match characters up to, but not including, a semi-colon or to the end of the string.
    0 讨论(0)
  • 2020-11-22 04:38

    Apparently MDN has never heard of the word-boundary regex character class \b, which matches contiguous \w+ that is bounded on either side with \W+:

    getCookie = function(name) {
        var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
        return r ? r[1] : null;
    };
    
    var obligations = getCookie('obligations');
    
    0 讨论(0)
  • Get cookie by name just pass the name of cookie to below function

    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 "";
    }
    
    0 讨论(0)
  • 2020-11-22 04:39

    I have done it this way. so that i get an object to access to separate the values.With this u can pass the cookie to the parent and then you can access your values by the keys like

    var cookies=getCookieVal(mycookie);
    alert(cookies.mykey);
    function getCookieVal(parent) {
                var cookievalue = $.cookie(parent).split('&');
                var obj = {};
                $.each(cookievalue, function (i, v) {
                    var key = v.substr(0, v.indexOf("="));
                    var val = v.substr(v.indexOf("=") + 1, v.length);
    
                    obj[key] = val;
    
                });
                return obj;
            }  
    
    0 讨论(0)
提交回复
热议问题