Javascript reading a cookie function

Sometimes you simply wish to read a certain cookie by javascript set by the server to see if a setting is true.

I use this simple function for that. All you have to provide is the name of the cookie and it will be read out and return the value.

function getSpecificCookie(which)
 {
 var i, x, y, ARRcookies = document.cookie.split(';');
 for (i = 0; i < ARRcookies.length; i++) 
  {
  x = ARRcookies[i].substr(0, ARRcookies[i].indexOf('='));
  y = ARRcookies[i].substr(ARRcookies[i].indexOf('=') + 1);
  x = x.replace(/^\s+|\s+$/g, '');
  if (x == which) 
   {
   return y;
   } 
  }
 return null;
 }

If no matching cookie has been found the function will return null so you have something to test against.

Comments

Popular Posts