Matt
Matt

Reputation: 5095

Retrieve Cookie Content

I'm trying tof ind a way to retrieve the content of a cookie in javascript.

Let's assume that the cookie is named "Google"

and lets also assume content of this cookie is just "blah"

I've been looking online and all I find are complex functions, and what I was wondering if there is a simple one line such code that retreives the value of the content in a cookie'

such as -

var myCookie = cookie.content('Google');

I don't want long parsers to check for various cookies or if the cookies have multiple value or whatever..Thanks!

Upvotes: 0

Views: 3767

Answers (5)

user1014351
user1014351

Reputation: 447

In javascript all cookies are stored in a single string. THe cookies are separated by a ; A possible function to read cookies is:

function readCookie(myCookieName)
{
  if (document.cookie.length > 0)
  {
    var start = document.cookie.indexOf(myCookieName + "=");
    if (start != -1)
    {
      start = start + myCookieName.length + 1;
      var end = document.cookie.indexOf(";",start);
      if (end == -1) end = document.cookie.length;
      return unescape(document.cookie.substring(start ,end ));
    }else{
      return "";
    }
  }
  return "";
}

Upvotes: 0

Porco
Porco

Reputation: 4203

You can use document.cookie, or document.cookie.split(';') to get a full list of key/values.

Upvotes: 0

mu is too short
mu is too short

Reputation: 434615

You'll have to parse the cookie jar yourself but it isn't that hard:

var name    = 'the_cookie_you_want';
var value   = null;
var cookies = document.cookie.split(/\s*;\s*/);
for(var i = 0; i < cookies.length; i++) {
    if(cookies[i].substring(0, name.length + 1) == (name + '=')) {
        value = decodeURIComponent(cookies[i].substring(name.length + 1));
        break;  
    }
}

Upvotes: 0

RealHowTo
RealHowTo

Reputation: 35372

Not exactly a simple one-line solution but close!

var results = document.cookie.match ( '(^|;) ?' + cookiename + '=([^;]*)(;|$)' );
if ( results ) myCookie = decodeURIComponent(results[2] ) ;

Upvotes: 1

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

QuirksMode has a very simple, but effective cookie script.

var Google = readCookie("Google"); // Google is now "blah"

Upvotes: 1

Related Questions