3

I am working from this thread:

What is the shortest function for reading a cookie by name in JavaScript?

Which shows that a cookie can be read in JavaScript using the following code:

function read_cookie(key)
{
    var result;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? (result[1]) : null;
}

I have a cookie which is set called "country" and its value is two letters, for example "AZ". I am wondering how one goes about reading the value of the cookie and putting it into a variable called cookie_country for example. This regexp is a little above me and I dont know where to start.

Community
  • 1
  • 1
Jimmy
  • 12,087
  • 28
  • 102
  • 192

2 Answers2

3

This...

var cookie_country = read_cookie('country');

... should be enough for this case. ) The point of this function (as many others) is that it provides you just a tool for extracting a value from document.cookie string by some string key ('country', in your case): you don't need to know how exactly this tool works unless it breaks. )

...But anyway, perhaps it would be interesting to know this as well. ) document.cookie is actually a string containing a semicolon-separated list of cookies (its key and its value). Here's more to read about it (MDN).

The regex basically catches the part of this string that matches the given string either at the beginning of the line or at the end of some ;, then goes on until, again, either the string ends of another semicolon appears.

For example, if key parameter is equal to country, the regex will look like this:

/(?:^|; )country=([^;]*)/

... and it will capture the value that is stored in document.cookie associated with country string.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
0

I guess you'll have to read the cookie line-by-line.

var rows = document.cookie.split(;);
for (i=0;i<rows.length;i++)
{
    var firstrow = rows[i].substr(0,rows[i].indexOf("="));
}

While creating you could put the variables to be between identifiers, something like AZ The regex should look like this: '##[AZ]{2}##'

Ofcourse, I could be completely wrong :)

Hope this helps.

DerpyNerd
  • 4,743
  • 7
  • 41
  • 92
  • 1
    While you gave an answer of how to read a cookie, the questioner asked how to read a cookie using the given function. So this answer is incorrect. – ErikE Nov 12 '12 at 23:49
  • I noticed that too late, sorry. Maybe I was confused with the fact that questioner was using a regex to find values in his cookie :s – DerpyNerd Nov 13 '12 at 12:12