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”
(‘; ‘ + 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”
.split(‘; ‘ + key + ‘=’)
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”]
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”
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”]
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.
('; '+document.cookie).split('; '+key+'=').pop().split(';').shift()
Source: Guilherme Rodrigues