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. :)