To find a particular cookie, you can use a Regular Expression to
look for the pattern of name=value, where the value ends with a ;
or the end of document.cookie. In this example, use any var name
you wish, and where I wrote cookname, put in the name of the
particular cookie you are looking for . (I would avoid using
spaces or special characters in cookie names.) m[0] is the
complete name=value string, m[1] just the value (after the =)
Caution: If you had cookies named both "firstname" and
"me", both would match "me" so you wouldn't know which value you
got. (see below)
var cookval var m = /cookname\=([^\;]+)/.exec(document.cookie) if (m) cookval = m[1] // the part in the ( ) else
/* -- that cookie isn't there ---*/
If you are expecting lots of cookies, you could use my function
cookies_array (it "splits" the cookie string twice) and a version
of the for loop that is
similar to PHP's foreach
function cookies_array () // returns array like php's $_COOKIE, with existing cookies
{ //author Lin Jensen
var cookies=document.cookie.split("; ")
var a = new Array()
if (cookies[0]) // no cookies still gives one empty string
for (i in cookies) // i indexes the array
{
var c = cookies[i].split("=");
a[c[0]] = c[1]
}
return a;
}
var cook = cookies_array()
for (key in cook)
{document.writeln("<li>"+key+'='+cook[key]+'</li>');
// using RegExp: look for cookie name,=, everything up to ; (or end)This first looks for a cookie ending with name, in this example, followed by = and then one or more characters other than a ; the () capture all those characters.
var m = /name\=([^\;]+)/i.exec(document.cookie)
if (m) document.write("Welcome back "+m[1]+"<br>")