Mental Jetsam

By Peter Finch

Get HTTP cookies as associative array in Javascript.

Posted by pcfinch on March 23, 2010

The following snippet of Javscsript code can be used to retrieve a documents cookies as an associative array so that the values can be easily retrieved using associative array lookup methods like cookies[“username”] or cookies.username .

function getCookies() {
    var cookies = document.cookie.split( ';' );
    var list = {} ; 
    for ( i = 0; i < cookies.length; i++ ) {
        var cv = cookies[i].split( '=' );
        var name = cv[0].replace(/\s+/g, "").replace(/\s+$/g,"") ;
        list[name] =  cv[1] ;
   return (list) ; 
cookies = getCookies() ;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: