spacer
Yehuda Shiran January 11, 2002
Getting Cookies
Tips: January 2002

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Eclipse Helios Update Brings New PHP Tools
Internet Explorer 9 Ups Standards Support
JBoss Portal 5 Release Easier to Use

One way to store and retrieve data on the client side is by using cookies. The cookie property is a member of the document object. You can store thousands of cookies per client. You can get a cookie with the following getCookie() function:

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}
where name is the name of the cookie as you stored it originally. The function getCookie() returns a string containing the value of the specified cookie or null if cookie does not exist.

The cookie property includes all cookies that were set for a particular page. The requested cookie may or may not be the first one in the cookie property. The function first assembles the string to search in the cookie, assuming it is not the first one. The string is concatenated from a semicolon, the name of the cookie, and an equal sign. If, for example, the name of the cookie is "kuku", then the string to search is ";kuku=". If there is no match, the possibility of being the first on the cookie property is considered. If it is not found, a null value is returned:

    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
Once a match is found, (begin != 0), we look for the end of the string or the following semicolon, and extract the string up to it:

  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));

People who read this tip also read these tips:

Look for similar tips by subject:

webref The latest from WebReference.com Browse >
Flashmaps' DynamicLocator: Interactive Maps for Small Areas · Flashmaps' AreaSelector: Interactive Maps for Wide Areas · The DB Mapper: Interactive Street-level Maps of U.S. and Canada
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
MS Access and MySQL · Cisco AutoQoS: VoIP QoS for Mere Mortals · While VoIP Adoption Explodes in Enterprise, Carrier Spending Lags