Code Premix

How to retrieve specific Cookies by Name in JavaScript

šŸ“…June 8, 2023
šŸ—JavaScript

Cookies are widely used for storing data in web applications, and being able to fetch specific cookies is a crucial skill. We present two methods to accomplish this task: one employing a Regular Expression pattern matching approach, and the other involving iterating through the cookie array.

Whether youā€™re a beginner or an experienced JavaScript developer, this article will equip you with the knowledge to efficiently retrieve cookies by name, empowering you to enhance your web applicationā€™s functionality. Letā€™s dive in and explore these methods step by step!

Method 1: Using Regular Expression

In this method, we utilize a Regular Expression to extract the cookie value by matching the name.

const getCookieByName = name => (
  document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || ''
);

Method 2: Iterating through Cookie Array

Here is an alternative approach to retrieve the cookie by name.

const getCookieByName = name => {
    // Split the cookie string and get individual name=value pairs in an array
    var cookieArr = document.cookie.split(";");

    // Loop through the array elements
    for (var i = 0; i < cookieArr.length; i++) {
        var cookiePair = cookieArr[i].split("=");

        // Remove whitespace at the beginning of the cookie name and compare it with the given string
        if (name == cookiePair[0].trim()) {
            // Decode the cookie value and return it
            return decodeURIComponent(cookiePair[1]);
        }
    }

    // Return null if the cookie is not found
    return null;
};

Thatā€™s it for today.

We hope you find these methods helpful in retrieving cookies by name in JavaScript. Thank you for reading, and happy coding! šŸ™‚