My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Wednesday, December 09, 2009

Two Step Backward: Read Cookies!

OK, I am the first one with non updated examples in devpro, but today just as curiosity I decided to have a look into every cookie related piece of library.

Apparently to retrieve cookies we have loops, splits, multiple RegExp, and any other sort of alchemy ... but are these functions the only one we need to read cookies?

var Cookie = {
get:function (name) {
var match = document.cookie.match(
new RegExp("(?:^|;\\s*)" + name + "=([^;]*?)", "g")
);
return match && match[1];
},
getAll:function () {
var re = new RegExp("([^=]+?)=([^;]*?)(?:;\\s*|$)", "g"),
cookie = "" + document.cookie,
result = {},
match
;
while(match = re.exec(cookie))
result[match[1]] = match[2]
;
return result;
}
};

I think sometimes we overload methods without a valid reason, but maybe I am missing something ... the only option I could eventually spot is the encode/decode, but as far as I know that is a browser problem, is it?
If we need that, well ...

var Cookie = {
get:function (name, encoded) {
var match = document.cookie.match(
new RegExp("(?:^|;\\s*)" + (encoded ? encodeURIComponent(name) : name) + "=([^;]*?)", "g")
);
return match && decodeURIComponent(match[1]);
},
getAll:function (encoded) {
var re = new RegExp("([^=]+?)=([^;]*?)(?:;\\s*|$)", "g"),
cookie = "" + document.cookie,
result = {},
match
;
while(match = re.exec(cookie))
result[encoded ? decodeURIComponent(match[1]) : match[1]] =
encoded ? decodeURIComponent(match[2]) : match[2];
;
return result;
}
};

1 comment:

  1. Hi Andrea,
    to make your get cookie works I need to modify you regexp in this way:

    "(?:^|;\\s*)" + name + "=([^;]*?)(?:\\s*(?:$|;))"

    Because ([^;]*?) trays to match nothing...

    I don't know why, but I've also to remove the g modifier...

    ReplyDelete

Note: Only a member of this blog may post a comment.