Home > Web Front-end > JS Tutorial > How to Retrieve a Specific Cookie by Name in JavaScript?

How to Retrieve a Specific Cookie by Name in JavaScript?

Barbara Streisand
Release: 2024-12-13 07:16:11
Original
584 people have browsed it

How to Retrieve a Specific Cookie by Name in JavaScript?

Get Cookie by Name for Specific Cookie

In the provided code, the getCookie1 function aims to retrieve the value of a cookie named "obligations". However, it overlooks that there may be other cookies present with different names.

To address this issue, we can modify the function to focus specifically on the "obligations" cookie:

function getCookie(name) {
  // Split the cookie string into an array of key-value pairs
  const elements = document.cookie.split("; ");

  // Iterate over the key-value pairs
  for (let i = 0; i < elements.length; i++) {
    const [cookieName, cookieValue] = elements[i].split("=");

    // Check if the cookie name matches the provided name
    if (cookieName === name) {
      return cookieValue;
    }
  }

  // No cookie with the provided name found
  return null;
}

const obligationsValue = getCookie("obligations");
Copy after login

In this updated code, we:

  1. Split the cookie string into an array of key-value pairs, where each pair is represented as a string in the format "key=value".
  2. Iterate over each key-value pair and split it into the cookie name and value.
  3. Check if the cookie name matches the provided "obligations" name.
  4. If a match is found, return the cookie value.
  5. Otherwise, continue iterating until all key-value pairs are processed.
  6. If no match is found, return null to indicate that no cookie with the provided name exists.

Using this function, you can now retrieve the value of the "obligations" cookie specifically, avoiding the issue of searching through all cookies and potentially mixing up their values.

The above is the detailed content of How to Retrieve a Specific Cookie by Name in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template