Reputation: 2482
I am using prototype and I can't find any built in extensions to set or retrieve cookies. After googling for a little bit, I see a few different ways to go about it. I was wondering what you think is the best approach for getting a cookie in JavaScript?
Upvotes: 6
Views: 17628
Reputation: 3732
In case anyone else needs it, I've fixed up Diodeus's code to address PhiLho's concern about partial matches when trying to fetch a cookie value.
function getCookie(c_name) {
var nameEQ = c_name + '=';
var c_start = 0;
var c_end = 0;
if (document.cookie.substr(0, nameEQ.length) === nameEQ) {
return document.cookie.substring(nameEQ.length, document.cookie.indexOf(';', nameEQ.length));
} else {
c_start = document.cookie.indexOf('; ' + nameEQ);
if(c_start !== -1){
c_start += nameEQ.length + 2;
c_end = document.cookie.indexOf(';', c_start);
if (c_end === -1) {c_end = document.cookie.length;}
return document.cookie.substring(c_start, c_end);
}
}
return null;
}
I've recently also built a much more compact RegExp that should work as well:
function getCookie(c_name){
var ret = window.testCookie.match(new RegExp("(?:^|;)\\s*"+c_name+"=([^;]*)"));
return (ret !== null ? ret[1] : null);
}
I did some speed tests that seem to indicate that out of PhiLo, QuirksMode, and these two implementations the non-RegExp version (using indexOf is very fast, not a huge surprise) above is the fastest. http://jsperf.com/cookie-fetcher
Upvotes: 2
Reputation: 41132
I use this routine:
function ReadCookie(name)
{
name += '=';
var parts = document.cookie.split(/;\s*/);
for (var i = 0; i < parts.length; i++)
{
var part = parts[i];
if (part.indexOf(name) == 0)
return part.substring(name.length)
}
return null;
}
Works quite well.
Upvotes: 9
Reputation: 1927
Anytime I need to access it, I use document.cookie, basically how it's outlined in that article. Caveat, I've never used prototype, so there may be easier methods there that you just haven't run across.
Upvotes: 2
Reputation: 114367
I use this. It has been dependable:
function getCookie(c_name) {
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1)
{
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return ""
}
Upvotes: -2