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

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

    The following function will allow differentiating between empty strings and undefined cookies. Undefined cookies will correctly return undefined and not an empty string unlike some of the other answers here.

    function getCookie(name) {
        return (document.cookie.match('(^|;) *'+name+'=([^;]*)')||[])[1];
    }
    

    The above worked fine for me on all browsers I checked, but as mentioned by @vanovm in comments, as per the specification the key/value may be surrounded by whitespace. Hence the following is more standard compliant.

    function getCookie(name) {
        return (document.cookie.match('(?:^|;)\\s*'+name.trim()+'\\s*=\\s*([^;]*?)\\s*(?:;|$)')||[])[1];
    }
    

提交回复
热议问题