Jimmy
Jimmy

Reputation: 12487

Use this JavaScript to load cookie into variable

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.

Upvotes: 3

Views: 1267

Answers (2)

DerpyNerd
DerpyNerd

Reputation: 4803

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.

Upvotes: 0

raina77ow
raina77ow

Reputation: 106385

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.

Upvotes: 3

Related Questions