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

How Can I Retrieve a Specific Cookie Value by Name in JavaScript?

Susan Sarandon
Release: 2024-12-11 07:15:11
Original
168 people have browsed it

How Can I Retrieve a Specific Cookie Value by Name in JavaScript?

Targeting Specific Cookies with "Get Cookie by Name" Functionality

In web development, cookies are often used to store and retrieve information about user sessions. When accessing cookies, it's essential to be able to target specific cookies by name.

Challenge:

Consider the following getter function that retrieves cookie values:

function getCookie1() {
    var elements = document.cookie.split('=');
    var obligations= elements[1].split('%');
    // ...
}
Copy after login

This function retrieves values from all cookies in the browser. However, we want to modify it to only retrieve values from a specific cookie named "obligations=".

Solution:

To achieve this, we can utilize a more targeted approach:

function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
}
Copy after login

Explanation:

  • split(; ${name}=): This line splits the cookie string (prepended with "; ") by the target cookie name enclosed in "; ".
  • if (parts.length === 2): This condition checks if a cookie with the specified name exists.
  • parts.pop(): This removes the part of the string containing the cookie value.
  • split(';').shift(): This splits the remaining string by ";" and extracts the cookie value.

By using this function, we can ensure that only values from the "obligations=" cookie are retrieved.

The above is the detailed content of How Can I Retrieve a Specific Cookie Value 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