Reading cookies the regular expression way

1 min read 0 comments Report broken page

While taking a look on the 2nd 24ways article for 2009, I was really surprised to read that ā€œThe Web Storage API is basically cookies on steroids, a unhealthy dosage of steroids. Cookies are always a pain to work with. First of all you have the problem of setting, changing and deleting them. Typically solved by Googling and blindly relying on PPKā€™s solution.ā€ (bold is mine)

Of course, thereā€™s nothing wrong with PPKā€™s solution. It works just fine. However, I always thought his readCookie() function was too verbose and complicated for no reason. Itā€™s a very common example of someone desperately trying to avoid using a regular expression. I googled for ā€œjavascript read cookieā€ and to my surprise, all examples found in the first results were very similar. I never understood why even experienced developers are so scared of regular expressions. Anyway, if anyone wants a shorter function to read a cookie, hereā€™s what I use:

function readCookie(name) { // Escape regexp special characters (thanks kangax!) name = name.replace(/([.*+?^=!:${}()|[\]\/\\])/g, ā€˜\\$1ā€™);

var regex = new RegExp(ā€˜(?:^|;)\\s?ā€™ + name + ā€˜=(.*?)(?:;|$)ā€™,ā€˜iā€™), match = document.cookie.match(regex);

return match && unescape(match[1]); // thanks James! }

Update: Function updated, see comments below.

Iā€™ve been using it for years and it hasnā€™t let me down. :)

Probably lots of other people have come up and posted something similar before me (I was actually very surprised that something like this isnā€™t mainstream), but Iā€™m posting it just in case. :)