Home  >  Article  >  Web Front-end  >  How to Read Cookies in Javascript: Shortest, Fastest, and Most Reliable?

How to Read Cookies in Javascript: Shortest, Fastest, and Most Reliable?

Susan Sarandon
Susan SarandonOriginal
2024-11-08 01:16:02567browse

 How to Read Cookies in Javascript: Shortest, Fastest, and Most Reliable?

Concise Cookie Reading in JavaScript: Optimizing for Size and Performance

When working with stand-alone JavaScript scripts without external dependencies, finding the optimal solution for reading cookies is crucial. The QuirksMode.org readCookie() function, while functional, is bulky and inefficient.

Improved jQuery.cookie Approach:

The read_cookie() function used by jQuery.cookie is more compact than readCookie():

function read_cookie(key)
{
    var result;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? (result[1]) : null;
}

However, further optimizations are possible.

Shortest and Most Efficient Solution:

const getCookieValue = (name) => (
  document.cookie.match('(^|;)\s*' + name + '\s*=\s*([^;]+)')?.pop() || ''
)

This approach leverages a regular expression to extract the desired cookie value, handling optional whitespace around the semicolon and equals sign. It also eliminates the need for multiple loops, making it significantly faster than other solutions.

Performance Comparison:

A performance comparison using jsben.ch demonstrates the superiority of the suggested solution:

https://jsben.ch/AhMN6

Key Advantages:

  • Concise: Only 18 characters (minified).
  • Reliable: Accounts for optional whitespace according to the official spec.
  • Performant: Significantly faster than other methods in most browsers.

The above is the detailed content of How to Read Cookies in Javascript: Shortest, Fastest, and Most Reliable?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn