View Full Version : Most efficient code to retrieve a cookie value?

01-21-2005, 12:32 PM
So I've been using the function:

function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
return returnvalue;

//ie: get_cookie("username")
to retrieve the value of a cookie in a name/value pair. I'm looking to roll my own soon using regular expressions, since the above is too chunky IMO. But I'm posting to see if anyone else wants to take a stab first. Just from the look of it I'm thinking just one line of code using regular expressions should do it.

The RE techniques used should be as cross browser/ OS functional as possible. I've seen RE that don't work in IE5, for example. So whoever's got some time on their hands...

01-21-2005, 01:30 PM
I didn't test this very thoroughly, but it worked for a quick test in Mozilla and IE5-6. sorry, those are the only browers I have.

function get_cookie(Name)
return (document.cookie.match(new RegExp(Name + "=([^;]+)"))) ? unescape(RegExp.$1) : "";

Willy Duitt
01-21-2005, 01:41 PM
Mines much the same but also checks for end of string in the event of multiple name/value pairs and the last pair is not followed by a comma seperator... But I like jmccaskill's use of the ternary better...

<script type="text/javascript">
document.cookie='username=willy,password=test'; alert(document.cookie);
function getCookie(name){
if(document.cookie && new RegExp('('+name+'=[a-z]+)(?=,|\$)','gi').test(document.cookie)){
} else alert('Not Present');

<body onload="getCookie('password');getCookie('username')">


01-21-2005, 11:48 PM
Interesting codes! Gives me some inspiration and direction. I'm going to try and come up with my own and post it here, and also test out your versions later.