Get cookie by name

前端 未结 30 1376
野的像风
野的像风 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:29

    A functional approach to find existing cookies. It returns an array, so it supports multiple occurrences of the same name. It doesn't support partial key matching, but it's trivial to replace the === in the filter with a regex.

    function getCookie(needle) {
        return document.cookie.split(';').map(function(cookiestring) {
            cs = cookiestring.trim().split('=');
    
            if(cs.length === 2) {
                return {'name' : cs[0], 'value' : cs[1]};
            } else {
                return {'name' : '', 'value' : ''};
            }
        })
        .filter(function(cookieObject) { 
            return (cookieObject.name === needle);
        });
    }
    
    0 讨论(0)
  • 2020-11-22 04:30

    I would prefer using a single regular expression match on the cookie:

    window.getCookie = function(name) {
      var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
      if (match) return match[2];
    }
    

    OR Also we are able to use as a function , check below code.

    function check_cookie_name(name) 
        {
          var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
          if (match) {
            console.log(match[2]);
          }
          else{
               console.log('--something went wrong---');
          }
       }
    

    Improved thanks to Scott Jungwirth in the comments.

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

    Simple function for Get cookie with cookie name:

    function getCookie(cn) {
        var name = cn+"=";
        var allCookie = decodeURIComponent(document.cookie).split(';');
        var cval = [];
        for(var i=0; i < allCookie.length; i++) {
            if (allCookie[i].trim().indexOf(name) == 0) {
                cval = allCookie[i].trim().split("=");
            }   
        }
        return (cval.length > 0) ? cval[1] : "";
    }
    
    0 讨论(0)
  • 2020-11-22 04:30

    In my projects I use following function to access cookies by name

    function getCookie(cookie) {
        return document.cookie.split(';').reduce(function(prev, c) {
            var arr = c.split('=');
            return (arr[0].trim() === cookie) ? arr[1] : prev;
        }, undefined);
    }
    
    0 讨论(0)
  • 2020-11-22 04:30

    reference: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

    document.cookie = "test1=Hello";
    document.cookie = "test2=World";
    
    var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");
    
      alert(cookieValue);
    
    0 讨论(0)
  • 4 years later, ES6 way simpler version.

    function getCookie(name) {
      let cookie = {};
      document.cookie.split(';').forEach(function(el) {
        let [k,v] = el.split('=');
        cookie[k.trim()] = v;
      })
      return cookie[name];
    }
    

    I have also created a gist to use it as a Cookie object. e.g., Cookie.set(name,value) and Cookie.get(name)

    This read all cookies instead of scanning through. It's ok for small number of cookies.

    0 讨论(0)
提交回复
热议问题