Reading a Cookie using RegExp
Question: How do I retrieve a cookie with a given name using a regular expression?
Answer:
To read a cookie function readCookie(cookieName) { var re = new RegExp('[; ]'+cookieName+'=([^\\s;]*)'); var sMatch = (' '+document.cookie).match(re); if (cookieName && sMatch) return unescape(sMatch[1]); return ''; }This readCookie function is somewhat less readable than the
non-RegExp version
- but, as we will see, it is more flexible.
Let us walk through the function code, line by line.
Code walk-through:
The var re = new RegExp('[; ]'+cookieName+'=([^\\s;]*)'); // to get \s in regular expression, pass \\s to RegExp constructor!Our regular expression re is constructed to
match the desired cookie name preceded by a semicolon or a space [; ]
and followed by an equal sign = and (immediately after = )
a substring of non-whitespace non-semicolon characters [^\s;]* .
This non-whitespace non-semicolon substring, if found,
will be retained in the capturing group
([^\s;]*) .
The substring captured in the group will be precisely the cookie value
part of document.cookie .
var sMatch = (' '+document.cookie).match(re);In this line of code, we use the match() method to find the fragment of the string
(' '+document.cookie) match() is stored in the sMatch variable.
If there is no matching cookie, sMatch will be set to null .
If there is a match, sMatch will store an array of matched substrings:
the first element sMatch[0] contains the whole RegExp match (e.g.
MyCookie=CookieValue ). Subsequent elements of the array, sMatch[1] etc.,
will hold the substrings matched with each capturing group. Since we have only one capturing group,
sMatch[1] is the last element in the array;
it is in sMatch[1] that match() puts the cookie value we want to get.
if (cookieName && sMatch) return unescape(sMatch[1]); return '';Here, before returning the cookie value, we make sure that (1) cookieName is not empty and (2) there was actually a match.
The if condition combines the values cookieName and sMatch
in a Boolean context; so the if condition is true when cookieName is a non-empty string and
sMatch is not null . If so, we return the (unescaped) cookie value in sMatch[1] .
Otherwise, that is, when cookieName is empty or sMatch is null (no match),
the function returns an empty string.
Final remarks:
Our new function is easy to modify.
For example, to support not only alphanumeric cookieName=cookieName.replace(/([.\\+\-*:\/?!|^${}()\[\]])/g,'\\$1'); Or would you like to require only non-empty cookie values?
No problem: just replace the var re = new RegExp('[,; ]'+cookieName+'=([^\\s,;]*)')
Other potential modifications of the |
|
Copyright © 1999-2012, JavaScripter.net.