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.
This…
… 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.cookiestring 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.cookieis 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
keyparameter is equal tocountry, the regex will look like this:… and it will capture the value that is stored in
document.cookieassociated withcountrystring.