Reading a Cookie using RegExp

JavaScript FAQ | JavaScript Cookies FAQ  

Question: How do I retrieve a cookie with a given name using a regular expression?

Answer: To read a cookie

cookieName
that has been set by the
setCookie
function, you can use the following
RegExp
-based function:
function readCookie(cookieName) {
 var re = new RegExp('[; ]'+cookieName+'=([^\\s;]*)');
 var sMatch = (' '+document.cookie).match(re);
 if (cookieName && sMatch) return unescape(sMatch[1]);
 return '';
}
Cookie Name: 
 
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

readCookie
function takes
cookieName
as a parameter. First, we call the
RegExp
constructor to create a regular expression for finding a cookie by name:
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)
that matches the RegExp we just created. The value returned by
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
but also (exceedingly rare) cookie names with "dangerous" characters, we could add code preparing a potentially "bad"
cookieName
for use in the
RegExp
constructor:
cookieName=cookieName.replace(/([.\\+\-*:\/?!|^${}()\[\]])/g,'\\$1');

Or would you like to require only non-empty cookie values? No problem: just replace the

*
(match zero or more characters) with
+
(match one or more characters) in the RegExp capturing group
([...]*)
. Or maybe you want to allow not only semicolons but also commas, as cookie separators? Then simply use the characters
,;
instead of just
;
in your
RegExp
constructor call:
var re = new RegExp('[,; ]'+cookieName+'=([^\\s,;]*)')

Other potential modifications of the

readCookie
function are also straightforward, thanks to the flexibility of regular expressions. (Please refer to Regular Expressions Syntax for a review of the
RegExp
elements such as
[^...]
,
*
,
+
, or capturing groups in regular expressions.)

 

 

Copyright © 1996-2018, JavascriptFAQ.net.