Quick Tip: one liner cookie read

For all the obtuse native functions JavaScript offers (“wat”.blink()?), there isn’t a simple, native way to parse cookies and get the value of a single key.

The inter-webs, however, always provide. In my roamings, I have found what is now my favorite getCookie one-liner:

('; ' + document.cookie)
.split('; ' + key + '=')

Okay, that’s not exactly an one-liner, but only so that we can understand this beauty step by step.

Let’s assume we have the following cookie: “first=1; doit=2; cookies=3”

Line 1

(‘; ‘ + document.cookie)

Cookies are separated by semicolons. As we might be searching for the first key, it's useful to prefix the entire thing with a semicolon.

Our cookie now looks like this: “; first=1; doit=2; cookies=3”

Line 2

.split(‘; ‘ + key + ‘=’)

From MDN:

The split() method splits a String object into an array of strings by separating the string into substrings. When found, separator is removed from the string and the substrings are returned in an array.

Here, we split the string in two parts, creating an array.
The first part contains everything before our key. We can ignore that.
The second part contains everything after our key. Including the value.

Using the key "doit", this is what we would get: [“; first=1”, “2; cookies=3”]

Line 3


From MDN:

The pop method removes the last element from an array and returns that value to the caller

As I promised, we can ignore the first value in that array. Therefore, pop gives us the interesting part: “2; cookies=3”

Line 4


It’s pretty easy from now on, huh? We’re getting an array whose first index will contain our desired value. The result: [“2”, “ cookies=3”]

Line 5


From MDN:

The shift() method removes the first element from an array and returns that element. This method changes the length of the array.

For the grand finale, we extract the first value of the array.

Voilà: “2”

That’s it.


('; '+document.cookie).split('; '+key+'=').pop().split(';').shift()

Quick Tip: one liner cookie read was originally published in First Do It on Medium, where people are continuing the conversation by highlighting and responding to this story.

Source: Guilherme Rodrigues

Leave a Reply

Your email address will not be published.