259

What is the shortest, accurate, and cross-browser compatible method for reading a cookie in JavaScript?

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.

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;
}

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.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Yahel
  • 37,023
  • 22
  • 103
  • 153
  • 10
    Stored cookie data is kind of ugly, so any method to handle them will probably be as well. – mVChr Apr 12 '11 at 17:41
  • 5
    @mVChr seriously. At what point was it decided that cookies should be accessed from a semi-colon delimited string? When was that ever a good idea? – Yahel Apr 12 '11 at 17:44
  • 8
    Why is this question still open and why does it have a bounty? Are you really that desperate to save maybe 5 bytes??? –  May 05 '11 at 02:49
  • cookieArr = document.cookie.split(';').map(ck=>{return {[ck.split('=')[0].trim()]:ck.split('=')[1]}}) – vladimir.gorea Dec 21 '19 at 18:08

20 Answers20

332

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

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

A performance comparison of various approaches is shown here:

https://jsben.ch/AhMN6

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.

EscapeNetscape
  • 2,892
  • 1
  • 33
  • 32
Mac
  • 3,352
  • 1
  • 17
  • 4
  • 5
    I've just noticed that in Firefox, the regex approach I posted above is not as performant as the looping approach. The tests I'd run previously were done in Chrome, where the regex approach performed modestly better than other approaches. Nonetheless, it's still the shortest which addresses the question being asked. – Mac Aug 25 '14 at 17:03
  • 6
    Why does `getCookieValue(a, b)` take parameter `b`? – Brent Washburne Oct 19 '15 at 18:42
  • 3
    @BrentWashburne instead of writing `var b =`... you have `,b` in arguments and `b=` inside function. You can save 1 byte :D "var b" (4 bytes) ",bb" (3 bytes) – instead Oct 26 '15 at 15:18
  • 2
    Aside from the +1 in code golf, does that make the code any better? – Brent Washburne Oct 26 '15 at 15:55
  • 18
    Upvoted, but not for readability... took me a while to figure out what `a` and `b` do. – Gigi Jan 27 '16 at 17:50
  • 14
    Clever, but silly to write it that way to save 1 byte. – The Muffin Man May 26 '16 at 03:45
  • 2
    The question is literally asking for the **shortest** solution, so this should be the accepted answer imho. I'm looking for a short code snippet to read one cookie, but the accepted answer gives me a script to populate a global variable (which I have to keep track of from then on) and I still need to read from that global, make sure it's initialized etc. So the accepted answer is answering another question: How to read cookies as efficiently as possible. – Stijn de Witt Sep 08 '16 at 15:17
  • 7
    `a` parameter is not regex escaped, while it can be useful, it is not safe. Things like`getCookieValue('.*')` will return any random cookie – Vitim.us Dec 21 '16 at 16:06
  • well it matters if you are working on a site with 5000 average active users.. every byte counts – dvdmn Apr 29 '17 at 00:25
  • 1
    For anyone saying it's silly to save a byte.. look at what Google is doing with it's search page. It's insane the kind of optimizations they put in there. Multiplied by a billion, a single byte is a lot! (of course, the website I'm working on will get just as much traffic! :p ) – Stijn de Witt May 24 '17 at 08:37
  • Why did You replaced `b` from function parameter with `var b` inside function? – instead May 31 '17 at 02:08
  • Create the regexp once and use it over and over for better performance. – Jim Pedid Aug 20 '17 at 17:02
  • I have no idea what this thing is doing, but it works. – Matt Jun 13 '20 at 14:08
  • Should it return an empty string when there are no matches? For me `undefined` is a more intuitive return in this case, any cons? – bsmaniotto Sep 19 '20 at 12:55
  • You can save 5 bytes by adding `b` into function arguments, return `b[2]` instead of `b.pop()` and combine everything into return statement: `function getCookieValue(a,b){return(b=document.cookie.match('(^|;)\\s*'+a+'\\s*=\\s*([^;]+)'))?b[2]:''}` – vanowm Oct 10 '20 at 22:44
  • @vanowm He knows. It was an approved edit by another user, though [very](https://stackoverflow.com/revisions/25490531/3) - [painfully](https://stackoverflow.com/revisions/25490531/3) - [done](https://stackoverflow.com/revisions/25490531/4). Please read the existing comments before repeating what's already been said. Btw, Matt, you disappoint me. *Don't use it unless you understand it!* (and if you don't understand, ask!) ;^D – ruffin Jan 04 '21 at 16:47
  • @ruffin did you read my entire comment or you stopped at first comma? Perhaps read it through next time you comment. The only reason I "repeated" it, is to explain the changes in the proposed code below. And since the original question is about "shortest function", readability is not required – vanowm Jan 05 '21 at 03:41
  • @vanowm You missed my point; well done. Look at the question's history. I wasn't arguing that change's merits about shortness; I was saying *Mac agreed with you and the community edited that out*. That is, **the original answer used `getCookieValue(a,b)` and *was* shorter**. As of today, Mac hasn't been on SO since 2016. If you think it's a useful edit, don't make a comment rehashing what's already been discussed (see [links from my earlier comment](https://stackoverflow.com/questions/5639346/25490531?noredirect=1#comment115922594_25490531)); **suggest/make an reversion**. ◔_◔ – ruffin Jan 05 '21 at 14:39
  • @ruffin, No, seriously, did you read my entire comment after the comma or not? because you sure sound like you didn't. Who cares about b as parameter, yes, it was in the original code, woopeedoo! that's not the main point, there are other changes that not only shorten the code, but also improve performance.I see no point continue this discussion. – vanowm Jan 06 '21 at 01:42
  • If there ARE spaces before the next `;` delimiting the next cookie value, those spaces will be included as part of the returned value. – ErikE Feb 16 '21 at 21:31
  • RFC 2109 has been replaced TWICE. It's not current. See https://stackoverflow.com/questions/1969232/what-are-allowed-characters-in-cookies#1969339 for a more thorough and up-to-date discussion on characters allowed in cookies. – ErikE Feb 16 '21 at 23:54
  • If you are planning on using this code in IE you will need to modify it: the ?.pop() bit is called optional chaining and is [not supported](https://caniuse.com/?search=optional%20chaining). – Kevin Seymour Jan 17 '22 at 14:25
198

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]}
Ryan M
  • 18,333
  • 31
  • 67
  • 74
  • Scopes are only create when entering a function. Therefore, you could gather your two var declaration. – xavierm02 May 07 '11 at 20:12
  • @xavierm02 - What? You're talking about the `read_cookie(k,r)` piece, I'm assuming, but not sure what your commennt it :) The point of it is to define `r` as undefined and thus save the few bytes from typing `var r` –  May 07 '11 at 22:46
  • Nope, he's talking about defining `C` twice in the 1st function. However, you can gather all three declarations, not just two. You can do that: `var c = document.cookie.split('; '), C, i=c.length;` (defining the loop thus `for(;i>0;i--)`), and therefore removing all other `var` statements from the `readCookie()` function. – Félix Saparelli May 08 '11 at 07:23
  • oh, I wasn't even paying attention to the first function :) –  May 08 '11 at 08:35
  • The var C in the for loop is useless (C is already declares in this function scope) and you could take the i you use in the for loop and declare it with c and C a bit before in the code. – xavierm02 May 08 '11 at 10:26
  • And you should use --i insteand of i--. If I remember well, it's a bit faster. – xavierm02 May 08 '11 at 10:27
  • @xavierm02 - FYI I just tested that theory (I remember it as well) in Chrome & FF and neither show any speed difference over 1,000,000,000 calls to `x--` vs `--x`. (10,000,000 iteration loop with 100 `--` calls inside to minimize the impact of the loop itself) –  May 08 '11 at 17:07
  • Hm... In some implementations, it's faster. Because ++i returns the actual value that the variable has whereas i++ returns the old value, which means the two values coexist. But I can't remember in what browser it was. I don't even know if it was in JavaScript... – xavierm02 May 08 '11 at 21:09
  • 2
    Here you go : http://jsperf.com/pre-increment-vs-post-increment I was right, ++i is faster, at least if you get the value before and after. And that's what you do in a for loop. – xavierm02 May 08 '11 at 21:26
  • @xavierm02 - I'm using the dev version of chrome, which is probably why I didn't see a difference. ___post___ -increment is actually repeatedly 1% faster (with a 1.36% margin of error) for me than pre-increment according to that test vs the 27% slower that it shows for Chrome 11. Firefox 3.6 and 4 also show that they're dead-even. That being said, thanks for the test, it's nice to know that many browsers do run pre-increment faster so all things being equal I'll probably start doing that more often. –  May 09 '11 at 00:32
  • 1
    This function does not return the full value of the cookie if it contains an equals sign within the cookie value. You can change this by using substring to remove the cookie name instead of relying on the split `cookies[C[0]] = c[i].substring(C[0].length + 1);` – Kevin M Oct 16 '13 at 15:40
  • An argument called `c`, and an argument called `C`. Fail. That's just a shockingly bad idea. – T.J. Crowder Dec 09 '13 at 00:29
  • 1
    One important thing: Since the value of "cookies" is cached, new cookies or changed cookies from other windows or tabs will not become visible. You can avoid this issue by storing the string-value from document.cookie in a variable and check if it is unchanged on each access. – Andreas Apr 01 '15 at 15:41
  • @zyklus "Who tried to store high ascii cookie names?"/"Who uses double bytes ANYWHERE in JavaScript?" Anyone who lives outside USA. USA does not represent the whole world. "Minimizing code has use cases", of course, but if you care about script size, then it means your use case requires a more robust code that works for most inputs. You don't need to care that much about code size if you are not developing open-source or at scale. My intent is not to sound elitist, it is just to help for posterity, that is why comments exists, not to fight against better alternatives. – Fagner Brack Apr 25 '15 at 18:11
  • Fair enough, though I would argue that you shouldn't be using unicode in JS regardless as it needlessly doubles your file sizes. My shortened solutions weren't meant to be robust, I even acknowledged that they wouldn't fully work in the original answer. It was more of a challenge to see just how small I could get the code while still being functional in _almost all_ use cases. –  Apr 26 '15 at 02:42
  • what about cookieArray = document.cookie.split(';').map(ck=>{return {[ck.split('=')[0].trim()]:ck.split('=')[1]}}) – vladimir.gorea Dec 21 '19 at 18:05
24

Assumptions

Based on the question, I believe some assumptions / requirements for this function include:

  • It will be used as a library function, and so meant to be dropped into any codebase;
  • As such, it will need to work in many different environments, i.e. work with legacy JS code, CMSes of various levels of quality, etc.;
  • To inter-operate with code written by other people and/or code that you do not control, the function should not make any assumptions on how cookie names or values are encoded. Calling the function with a string "foo:bar[0]" should return a cookie (literally) named "foo:bar[0]";
  • New cookies may be written and/or existing cookies modified at any point during lifetime of the page.

Under these assumptions, it's clear that encodeURIComponent / decodeURIComponent should not be used; doing so assumes that the code that set the cookie also encoded it using these functions.

The regular expression approach gets problematic if the cookie name can contain special characters. jQuery.cookie works around this issue by encoding the cookie name (actually both name and value) when storing a cookie, and decoding the name when retrieving a cookie. A regular expression solution is below.

Unless you're only reading cookies you control completely, it would also be advisable to read cookies from document.cookie directly and not cache the results, since there is no way to know if the cache is invalid without reading document.cookie again.

(While accessing and parsing document.cookies will be slightly slower than using a cache, it would not be as slow as reading other parts of the DOM, since cookies do not play a role in the DOM / render trees.)


Loop-based function

Here goes the Code Golf answer, based on PPK's (loop-based) function:

function readCookie(name) {
    name += '=';
    for (var ca = document.cookie.split(/;\s*/), i = ca.length - 1; i >= 0; i--)
        if (!ca[i].indexOf(name))
            return ca[i].replace(name, '');
}

which when minified, comes to 128 characters (not counting the function name):

function readCookie(n){n+='=';for(var a=document.cookie.split(/;\s*/),i=a.length-1;i>=0;i--)if(!a[i].indexOf(n))return a[i].replace(n,'');}

Regular expression-based function

Update: If you really want a regular expression solution:

function readCookie(name) {
    return (name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1];
}

This escapes any special characters in the cookie name before constructing the RegExp object. Minified, this comes to 134 characters (not counting the function name):

function readCookie(n){return(n=new RegExp('(?:^|;\\s*)'+(''+n).replace(/[-[\]{}()*+?.,\\^$|#\s]/g,'\\$&')+'=([^;]*)').exec(document.cookie))&&n[1];}

As Rudu and cwolves have pointed out in the comments, the regular-expression-escaping regex can be shortened by a few characters. I think it would be good to keep the escaping regex consistent (you may be using it elsewhere), but their suggestions are worth considering.


Notes

Both of these functions won't handle null or undefined, i.e. if there is a cookie named "null", readCookie(null) will return its value. If you need to handle this case, adapt the code accordingly.

Jeffery To
  • 11,836
  • 1
  • 27
  • 42
18

code from google analytics ga.js

function c(a){
    var d=[],
        e=document.cookie.split(";");
    a=RegExp("^\\s*"+a+"=\\s*(.*?)\\s*$");
    for(var b=0;b<e.length;b++){
        var f=e[b].match(a);
        f&&d.push(f[1])
    }
    return d
}
VKen
  • 4,964
  • 4
  • 31
  • 43
ChicoDeFe
  • 181
  • 1
  • 2
  • I changed last line `return d[0];` and then I used `if (c('EXAMPLE_CK') == null)` to check if cookie is not defined. – electroid Sep 16 '15 at 14:41
10

How about this one?

function getCookie(k){var v=document.cookie.match('(^|;) ?'+k+'=([^;]*)(;|$)');return v?v[2]:null}

Counted 89 bytes without the function name.

Simon Steinberger
  • 6,605
  • 5
  • 55
  • 97
8

The following function will allow differentiating between empty strings and undefined cookies. Undefined cookies will correctly return undefined and not an empty string unlike some of the other answers here.

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

The above worked fine for me on all browsers I checked, but as mentioned by @vanovm in comments, as per the specification the key/value may be surrounded by whitespace. Hence the following is more standard compliant.

function getCookie(name) {
    return (document.cookie.match('(?:^|;)\\s*'+name.trim()+'\\s*=\\s*([^;]*?)\\s*(?:;|$)')||[])[1];
}
Joyce Babu
  • 19,602
  • 13
  • 62
  • 97
5

this in an object that you can read, write, overWrite and delete cookies.

var cookie = {
    write : function (cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays*24*60*60*1000));
        var expires = "expires="+d.toUTCString();
        document.cookie = cname + "=" + cvalue + "; " + expires;
    },
    read : function (name) {
        if (document.cookie.indexOf(name) > -1) {
            return document.cookie.split(name)[1].split("; ")[0].substr(1)
        } else {
            return "";
        }
    },
    delete : function (cname) {
        var d = new Date();
        d.setTime(d.getTime() - 1000);
        var expires = "expires="+d.toUTCString();
        document.cookie = cname + "=; " + expires;
    }
};
5

Here goes.. Cheers!

function getCookie(n) {
    let a = `; ${document.cookie}`.match(`;\\s*${n}=([^;]+)`);
    return a ? a[1] : '';
}

Note that I made use of ES6's template strings to compose the regex expression.

mfalade
  • 1,647
  • 2
  • 17
  • 16
5

It's 2022, everything except Internet Explorer supports the URLSearchParams API (^1) and String.prototype.replaceAll API (^2), so we can horribly (ab)use them:

const cookies = new URLSearchParams(document.cookie.replaceAll('&', '%26').replaceAll('; ', '&'));
cookies.get('cookie name'); // returns undefined if not set, string otherwise
Henry
  • 1,339
  • 13
  • 24
2

To truly remove as much bloat as possible, consider not using a wrapper function at all:

try {
    var myCookie = document.cookie.match('(^|;) *myCookie=([^;]*)')[2]
} catch (_) {
    // handle missing cookie
}

As long as you're familiar with RegEx, that code is reasonably clean and easy to read.

Abhi Beckert
  • 32,787
  • 12
  • 83
  • 110
2

Both of these functions look equally valid in terms of reading cookie. You can shave a few bytes off though (and it really is getting into Code Golf territory here):

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

All I did with this is collapse all the variable declarations into one var statement, removed the unnecessary second arguments in calls to substring, and replace the one charAt call into an array dereference.

This still isn't as short as the second function you provided, but even that can have a few bytes taken off:

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

I changed the first sub-expression in the regular expression to be a capturing sub-expression, and changed the result[1] part to result[2] to coincide with this change; also removed the unnecessary parens around result[2].

2

Get the cookie value or undefined if it doesn't exist:

document
  .cookie
  .split('; ')
  .filter(row => row.startsWith('cookie_name='))
  .map(c=>c.split('=')[1])[0];
Mariano Ruiz
  • 4,314
  • 2
  • 38
  • 34
1

Here is the simplest solution using javascript string functions.

document.cookie.substring(document.cookie.indexOf("COOKIE_NAME"), 
                          document.cookie.indexOf(";", 
                          document.cookie.indexOf("COOKIE_NAME"))).
  substr(COOKIE_NAME.length);
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Kumar
  • 407
  • 4
  • 6
1

To have all cookies accessible by name in a Map:

const cookies = "a=b ; c = d ;e=";
const map = cookies.split(";").map((s) => s.split("=").map((s) => s.trim())).reduce((m, [k, v]) => (m.set(k, v), m), new Map());
console.log(map); //Map(3) {'a' => 'b', 'c' => 'd', 'e' => ''}
map.get("a"); //returns "b"
map.get("c"); //returns "d"
map.get("e"); //returns ""
gogo
  • 950
  • 12
  • 20
0

(edit: posted the wrong version first.. and a non-functional one at that. Updated to current, which uses an unparam function that is much like the second example.)

Nice idea in the first example cwolves. I built on both for a fairly compact cookie reading/writing function that works across multiple subdomains. Figured I'd share in case anyone else runs across this thread looking for that.

(function(s){
  s.strToObj = function (x,splitter) {
    for ( var y = {},p,a = x.split (splitter),L = a.length;L;) {
      p = a[ --L].split ('=');
      y[p[0]] = p[1]
    }
    return y
  };
  s.rwCookie = function (n,v,e) {
    var d=document,
        c= s.cookies||s.strToObj(d.cookie,'; '),
        h=location.hostname,
        domain;
    if(v){
      domain = h.slice(h.lastIndexOf('.',(h.lastIndexOf('.')-1))+1);
      d.cookie = n + '=' + (c[n]=v) + (e ? '; expires=' + e : '') + '; domain=.' + domain + '; path=/'
    }
    return c[n]||c
  };
})(some_global_namespace)
  • If you pass rwCookie nothing, it will get all cookies into cookie storage
  • Passed rwCookie a cookie name, it gets that cookie's value from storage
  • Passed a cookie value, it writes the cookie and places the value in storage
  • Expiration defaults to session unless you specify one
Adam
  • 2,873
  • 3
  • 18
  • 17
0

Using cwolves' answer, but not using a closure nor a pre-computed hash :

// Golfed it a bit, too...
function readCookie(n){
  var c = document.cookie.split('; '),
      i = c.length,
      C;

  for(; i>0; i--){
     C = c[i].split('=');
     if(C[0] == n) return C[1];
  }
}

...and minifying...

function readCookie(n){var c=document.cookie.split('; '),i=c.length,C;for(;i>0;i--){C=c[i].split('=');if(C[0]==n)return C[1];}}

...equals 127 bytes.

Félix Saparelli
  • 8,424
  • 6
  • 52
  • 67
0

Just to throw my hat in the race, here's my proposal:

function getCookie(name) {
   const cookieDict = document.cookie.split(';')
        .map((x)=>x.split('='))
        .reduce((accum,current) => { accum[current[0]]=current[1]; return accum;}, Object());
    return cookieDict[name];
}

The above code generates a dict that stores cookies as key-value pairs (i.e., cookieDict), and afterwards accesses the property name to retrieve the cookie.

This could effectively be expressed as a one-liner, but this is only for the brave:

document.cookie.split(';').map((x)=>x.split('=')).reduce((accum,current) => { accum[current[0]]=current[1]; return accum;}, {})[name]

The absolute best approach would be to generate cookieDict at page load and then throughout the page lifecycle just access individual cookies by calling cookieDict['cookiename'].

RAM
  • 2,257
  • 2
  • 19
  • 41
0

This function doesn't work for older browser like chrome > 80.

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

I solved it by using this function instead that returns undefined if the cookie is missing:

function getCookie(name) {
  // Add the = sign
  name = name + '=';

  // Get the decoded cookie
  var decodedCookie = decodeURIComponent(document.cookie);

  // Get all cookies, split on ; sign
  var cookies = decodedCookie.split(';');

  // Loop over the cookies
  for (var i = 0; i < cookies.length; i++) {
    // Define the single cookie, and remove whitespace
    var cookie = cookies[i].trim();

    // If this cookie has the name of what we are searching
    if (cookie.indexOf(name) == 0) {
      // Return everything after the cookies name
      return cookie.substring(name.length, cookie.length);
    }
  }
}

Credit: https://daily-dev-tips.com/posts/vanilla-javascript-cookies-%F0%9F%8D%AA/

T. Smith
  • 3
  • 2
0

You can verify if a cookie exists and it has a defined value:

function getCookie(cookiename) {
    if (typeof(cookiename) == 'string' && cookiename != '') {
        const COOKIES = document.cookie.split(';');
        for (i = 0; i < COOKIES.length; i++) {
            if (COOKIES[i].trim().startsWith(cookiename)) {
                return COOKIES[i].split('=')[1];
            }
        }
    }

    return null;
}

const COOKIE_EXAMPLE = getCookie('example');
if (COOKIE_EXAMPLE == 'stackoverflow') { ... }
// If is set a cookie named "example" with value "stackoverflow"
if (COOKIE_EXAMPLE != null) { ... }
// If is set a cookie named "example" ignoring the value

It will return null if cookie doesn't exists.

Marco Concas
  • 1,665
  • 20
  • 25
0

On chromium based browsers you can use the experimental cookieStore api:

await cookieStore.get('cookieName');

Check the Browsersupport before using!

HaNdTriX
  • 28,732
  • 11
  • 78
  • 85