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

前端 未结 15 2115
猫巷女王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

    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'].

提交回复
热议问题