What is the shortest, accurate, and cross-browser compatible method for reading a cookie in JavaScript?
Very often, while building stand-alone scri
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.