What is the shortest function for reading a cookie by name in JavaScript?

前端 未结 15 1927
猫巷女王i
猫巷女王i 2020-11-22 17:17

What is the shortest, accurate, and cross-browser compatible method for reading a cookie in JavaScript?

Very often, while building stand-alone scri

相关标签:
15条回答
  • 2020-11-22 17:37

    Here goes.. Cheers!

    function getCookie(n) {
        let a = `; ${document.cookie}`.match(`;\\s*${n}=([^;]+)`);
        return a ? a[1] : '';
    }
    

    Note that I made use of ES6's template strings to compose the regex expression.

    0 讨论(0)
  • 2020-11-22 17:37

    Just to throw my hat in the race, here's my proposal:

    function getCookie(name) {
       const cookieDict = document.cookie.split(';')
            .map((x)=>x.split('='))
            .reduce((accum,current) => { accum[current[0]]=current[1]; return accum;}, Object());
        return cookieDict[name];
    }
    

    The above code generates a dict that stores cookies as key-value pairs (i.e., cookieDict), and afterwards accesses the property name to retrieve the cookie.

    This could effectively be expressed as a one-liner, but this is only for the brave:

    document.cookie.split(';').map((x)=>x.split('=')).reduce((accum,current) => { accum[current[0]]=current[1]; return accum;}, {})[name]
    
    

    The absolute best approach would be to generate cookieDict at page load and then throughout the page lifecycle just access individual cookies by calling cookieDict['cookiename'].

    0 讨论(0)
  • 2020-11-22 17:38

    How about this one?

    function getCookie(k){var v=document.cookie.match('(^|;) ?'+k+'=([^;]*)(;|$)');return v?v[2]:null}
    

    Counted 89 bytes without the function name.

    0 讨论(0)
  • 2020-11-22 17:40

    To truly remove as much bloat as possible, consider not using a wrapper function at all:

    try {
        var myCookie = document.cookie.match('(^|;) *myCookie=([^;]*)')[2]
    } catch (_) {
        // handle missing cookie
    }
    

    As long as you're familiar with RegEx, that code is reasonably clean and easy to read.

    0 讨论(0)
  • 2020-11-22 17:40

    Here is the simplest solution using javascript string functions.

    document.cookie.substring(document.cookie.indexOf("COOKIE_NAME"), 
                              document.cookie.indexOf(";", 
                              document.cookie.indexOf("COOKIE_NAME"))).
      substr(COOKIE_NAME.length);
    
    0 讨论(0)
  • 2020-11-22 17:41

    this in an object that you can read, write, overWrite and delete cookies.

    var cookie = {
        write : function (cname, cvalue, exdays) {
            var d = new Date();
            d.setTime(d.getTime() + (exdays*24*60*60*1000));
            var expires = "expires="+d.toUTCString();
            document.cookie = cname + "=" + cvalue + "; " + expires;
        },
        read : function (name) {
            if (document.cookie.indexOf(name) > -1) {
                return document.cookie.split(name)[1].split("; ")[0].substr(1)
            } else {
                return "";
            }
        },
        delete : function (cname) {
            var d = new Date();
            d.setTime(d.getTime() - 1000);
            var expires = "expires="+d.toUTCString();
            document.cookie = cname + "=; " + expires;
        }
    };
    
    0 讨论(0)
提交回复
热议问题