Open In App

How to Get Cookie by Name in JavaScript?

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Getting a specific name in JavaScript involves parsing the document's cookie string contains all cookies in a single string separated by semicolons and space. The goal is to extract the value of a specific cookie by the name given.

The Cookie is defined as a small piece of data that is stored on the user's computer by the web browser while browsing a website. Cookies are designed to be a reliable mechanism for websites to remember stateful information by the user's browsing activity. They can be used for various purposes such as session management, personalization, and tracking.

These are the following approaches:

Types of Cookies

We provide types of cookies for your reference.

  • Session Cookies: These cookies are temporary and are deleted from the user's device when the browser is closed. They are used to store session-specific information.
  • Persistent Cookies: These cookies remain on the users device for a set period until they are deleted. They are used to remember login information and settings between sessions.
  • Secure Cookies: These cookies can only be transmitted over secure HTTPS connections ensuring that they are encrypted during transmission.
  • HttpOnly Cookies: These cookies can not be accessed via JavaScript and can only be sent in HTTP requests.
  • SameSite Cookies: These cookies include a SameSite attribute that controls whether a cookie is sent with cross origin requests providing some protection against cross site request forgery attacks.

Properties of Cookies

  • Name: The name of the cookie.
  • Value: The value of the cookie.
  • Domain: Domain for which the cookie is valid. It can be specific domain or sub domain.
  • Path : URL path for which the cookie is valid.
  • Expires : The data and time when cookie will expire.
  • Max Age : The maximum age of the cookie will expire.
  • Secure : Indicates that cookie should only be sent over secure HTTPS connections.
  • HttpOnly : Indicates that the cookie is inaccessible to JavaScript document.cookie API offering better protection against XSS attack.
  • SameSite: Controls whether the cookies should be sent with cross site requests. It can have values of Strict, Lax, None

Using a Simple Function to Parse Cookies

This approach involves writing a function that splits the document.cookie string and loop through the resulting array to find the cookie with the desired name.

Syntax:

function getCookieByName(name) {
const cookies = document.cookie.split(';');
for (let cookie of cookies) {
cookie = cookie.trim();
if (cookie.startsWith(name + '=')) {
return cookie.substring(name.length + 1);
}
}
return null;
}

Example: This example shows the creation of a single function to get the cookie value.

JavaScript
document.cookie = "username=JohnDoe";

function getCookieByName(name) {
  const cookies = document.cookie.split(";");
  for (let cookie of cookies) {
    cookie = cookie.trim();
    if (cookie.startsWith(name + "=")) {
      return cookie.substring(name.length + 1);
    }
  }
  return null;
}

console.log(getCookieByName("username"));

Output:

111
output

Using the document.cookie Property Directly and Manually Parsing

This method involves directly accessing document.cookie splitting it into individual cookies and iterating through them manually to find the desired cookie.

Syntax:

function getCookieByName(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(';');
for(let i=0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length,c.length);
}
return null;
}

Example: This example shows the use of document.cookie property to get the name of cookie.

JavaScript
document.cookie = "username=GeeksForGeeks";

function getCookieByName(name) {
    const nameEQ = name + "=";
    const ca = document.cookie.split(';');
    for(let i=0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) 
        return c.substring(nameEQ.length,c.length);
    }
    return null;
}

console.log(getCookieByName("username")); 

Output:

111
output

This approach users a regular expression to search for the cookie name and extract its vale.

Syntax:

function getCookieByName(name) {
const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
if (match) return match[2];
return null;
}

Example: This example shows the use of regular expression to get the value of cookie.

JavaScript
document.cookie = "username=GFG";

function getCookieByName(name) {
  const match = document.cookie
                .match(new RegExp("(^| )" + name + "=([^;]+)"));
  if (match) return match[2];
  return null;
}

console.log(getCookieByName("username"));


Output:

111
output

Next Article

Similar Reads