在 JavaScript 中按名称读取 cookie 的最短函数是什么? [英] What is the shortest function for reading a cookie by name in JavaScript?

查看:23
本文介绍了在 JavaScript 中按名称读取 cookie 的最短函数是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JavaScript 中读取 cookie 的最短、准确且跨浏览器兼容的方法是什么?

很多时候,在构建独立脚本(我不能有任何外部依赖项)时,我发现自己添加了一个读取 cookie 的函数,并且通常回退到 QuirksMode.org readCookie() 方法(280 字节,216 缩小.)

Very often, while building stand-alone scripts (where I can't have any outside dependencies), I find myself adding a function for reading cookies, and usually fall-back on the QuirksMode.org readCookie() method (280 bytes, 216 minified.)

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

它可以完成这项工作,但它很丑陋,并且每次都增加了相当多的膨胀.

It does the job, but its ugly, and adds quite a bit of bloat each time.

jQuery.cookie 使用这样的方法(修改,165 字节,125 缩小):

The method that jQuery.cookie uses something like this (modified, 165 bytes, 125 minified):

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

注意这不是代码高尔夫"比赛:我对减少我的 readCookie 函数的大小以及确保我拥有的解决方案有效有合法的兴趣.

Note this is not a 'Code Golf' competition: I'm legitimately interested in reducing the size of my readCookie function, and in ensuring the solution I have is valid.

推荐答案

比当前的最佳投票答案更短、更可靠、性能更高:

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

此处显示了各种方法的性能比较:

A performance comparison of various approaches is shown here:

http://jsperf.com/get-cookie-value-正则表达式与数组函数

关于方法的一些注意事项:

regex 方法不仅在大多数浏览器中速度最快,而且生成的函数也最短.另外需要指出的是,根据官方规范(RFC 2109),空间在 document.cookie 中分隔 cookie 的分号之后是可选的,并且可以提出不应该依赖它的论点.此外,在等号 (=) 之前和之后允许有空格,并且可以提出一个论点,即这个潜在的空格应该被考虑到任何可靠的 document.cookie 解析器中.上面的正则表达式解释了上述两种空白条件.

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.

这篇关于在 JavaScript 中按名称读取 cookie 的最短函数是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆