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

前端 未结 15 2124
猫巷女王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条回答
  •  Happy的楠姐
    2020-11-22 17:33

    This will only ever hit document.cookie ONE time. Every subsequent request will be instant.

    (function(){
        var cookies;
    
        function readCookie(name,c,C,i){
            if(cookies){ return cookies[name]; }
    
            c = document.cookie.split('; ');
            cookies = {};
    
            for(i=c.length-1; i>=0; i--){
               C = c[i].split('=');
               cookies[C[0]] = C[1];
            }
    
            return cookies[name];
        }
    
        window.readCookie = readCookie; // or expose it however you want
    })();
    

    I'm afraid there really isn't a faster way than this general logic unless you're free to use .forEach which is browser dependent (even then you're not saving that much)

    Your own example slightly compressed to 120 bytes:

    function read_cookie(k,r){return(r=RegExp('(^|; )'+encodeURIComponent(k)+'=([^;]*)').exec(document.cookie))?r[2]:null;}
    

    You can get it to 110 bytes if you make it a 1-letter function name, 90 bytes if you drop the encodeURIComponent.

    I've gotten it down to 73 bytes, but to be fair it's 82 bytes when named readCookie and 102 bytes when then adding encodeURIComponent:

    function C(k){return(document.cookie.match('(^|; )'+k+'=([^;]*)')||0)[2]}
    

提交回复
热议问题