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

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

    Shorter, more reliable and more performant than the current best-voted answer:

    function getCookieValue(a) {
        var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)');
        return b ? b.pop() : '';
    }
    

    A performance comparison of various approaches is shown here:

    http://jsperf.com/get-cookie-value-regex-vs-array-functions

    Some notes on approach:

    The regex approach is not only the fastest in most browsers, it yields the shortest function as well. Additionally it should be pointed out that according to the official spec (RFC 2109), the space after the semicolon which separates cookies in the document.cookie is optional and an argument could be made that it should not be relied upon. Additionally, whitespace is allowed before and after the equals sign (=) and an argument could be made that this potential whitespace should be factored into any reliable document.cookie parser. The regex above accounts for both of the above whitespace conditions.

提交回复
热议问题