Get cookie value with regular expression

With this RegEx you can find and extract the value of a cookie.
If the cookie is not found (or has no value) an empty string "" is returned.
Note: It is also the most performant way to get a cookie value that I know of (more info).

function getCookieValueByName(name) {
    var match = document.cookie.match(new RegExp("(^| )" + name + "=([^;]+)"));
    return match ? match[2] : "";

Explanation of the code

Function wrap

function getCookieValueByName(param) {
        // ...

This way we are able to extract the cookie value. We can call this function for every cookie we want. Like so:

// wanting to get the value of "myCookie":

Parts of the function explained - part 1 - the regex

new RegExp("(^| )" + name + "=([^;]+)"
  1. Just this quick thing first:
    The regex might look confusing because of the " and + signs. So let me make it clear:
    Let's say we are looking for a cookie with name "myCookie". Then...

    new RegExp("(^| )" + "myCookie" + "=([^;]+)")
    simply becomes this regex:
    /(^| )myCookie([^;]+)/
    ... so that's the regex we are looking at now.
  2. As for the part (^| ):
    + With the ^ we are matching the beginning of the string. So it will match in case the cookie we are looking for is the first cookie in the document.cookie string.
    + With the empty space character   we are matching a whitespace character. It will match if the cookie we are looking for is not the first in the document.cookie string.
    + The | character in regular expressions works as an "or" operator.

    To make this clear again - this is how your document.cookie could look like. You can see the ; followed by a whitespace in between the two cookies. This whitespace is the match we are looking for.
    "_myExampleId=AB1.2.1234931.158812345; myPersonalCookie=valueOfMyCookie; myOtherCookie=someOtherValue"
    //key1_______=value1_________________; key2____________=value2_________; key3_________=value3________
  3. As for the part =([^;]+):
    Just for now ignore the brackets. Then the regex becomes this: =[^;]+
    (For more about brackets check the link at bottom of page).

    What this means is that we are matching exactly one = character followed by at least one character that is anything except a ;.
    The "everything but a ;" is signaled by [^;].
    The "at least one" is signaled by the use of the + character.

    This part will only match if there is at least one "non-semicolon" character after the =. Why this is important I'll explain further down.

Parts of the function explained - part 2 - the match

var match = document.cookie.match(...)

What we are doing here is simply matching our regex with the string document.cookie and storing the result in the variable match.
What is important to know here is the type of variables that .match() returns:

  • If the regex matches, the result will be of variable type Array.
  • If the regex does not match the result will be of value null (a JavaScript default value signalling that the variable is not set at all).

Parts of the function explained - part 3 - the return

return match ? match[2] : "";

The .match() method did all the work for us already: If our searched cookie was not inside document.cookie (or simply had no value) then our variable match will be of the JavaScript value null.

If our searched cookie was indeed inside document.cookie (and had some value) then our regex will return a variable of type Array.

This is where the brackets we used come into play. We use the brackets to make sure we can identify and re-use the parts of our regex. Our second part (bracket) is the part that is after the = character and holds the value of the cookie.

So because of this we can simply say that if we had a successful match then the function should give back only the second part of the regex - as stored in match[2].
If we did not have a match it will return an empty string ""

This is a ternary operator. For beginners the following will be easier to read (but does the exact same thing):
if (match) {return match[2]} else {return ""}

One note about performance

You might need to do operations on cookies very often or very early (while still loading the page). In those scenarios, performance is very important.

I tested many different implementations of this function. While there are other very performant ways to do this, this has (in my tests) turned out as the most performant way across different browsers to get a cookie value.

Further reading

get URL parameter (very similar case)
How to use brackets in regular expressions
Different ways of declaring RegExes

Was this page helpful?

Thank you for telling