How to manage cookies in JavaScript

At some point you'll want to read, set, and remove cookies using JavaScript. This is actually way more complicated than it should be so I'll provide a few example functions and refer you to a solid jQuery plugin.

1

First you should understand what the cookie is and how it's set. A cookie is a string that is stored on the user's computer to allow data to persist throughout the user's session. Cookies are often set by HTTP response headers, but they can also be set directly in the browser using JavaScript. To read the entire cookie string you can access document.cookie.

document.cookie
What you'll likely see is a long string of semi-colon delineated key/value pairs.
ps=31;_ssd3=P0-1415818163-1436218393727;favorite_animal=goat;_gaa=23.00334.....

2

You can manually set a cookie by setting document.cookie equal to the desired cookie using this format:

document.cookie = "name=tyler;expires=Thu, 03 Sep 2015 05:33:44 GMT";
This can be a little cumbersome, so the function below should make things easier.
function setCookie(name, value, exdays) {
    var d, expires;
    exdays = exdays || 1;
    d = new Date();
    d.setTime(d.getTime() + (exdays2460601000));
    expires = "expires=" + d.toUTCString();
    document.cookie = name + "=" + value + "; " + expires;
}
To set a cookie that lasts for one year, you could use:
setCookie('name', 'Batman', 365);

3

To read a cookie you can simply access document.cookie.

console.log(document.cookie);
If you're searching for a specific value you can use the following function.
function getCookie(name) {
    var cookie, c;
    cookies = document.cookie.split(';');
    for (var i=0; i < cookies.length; i++) {
        c = cookies[i].split('=');
        if (c[0] == name) {
            return c[1];
        }
    }
    return "";
}
This function uses JavaScript's string split method to split the cookie string by semi-colons. Then it loops through the result array of strings and splits them again by "=" producing the cookie key/value pair. Then it simply tests the cookie key (c[0]) against the name of the cookie you are trying to read. If it matches it returns the value (c[1]).

4

To delete a cookie, you simply need to expire it. So deleting a cookie is basically setting the cookie with an expiration in the past. Using our setCookie function:

setCookie('name', '', -1);

5

If you're using jQuery, you might as well use this cookie plugin. It allows easy management of cookies.

// read
$.cookie('name'); // => "Batman"
// set
$.cookie('name', 'Iron Man');
// delete
$.removeCookie('name');