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

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

Barbara Streisand
Release: 2024-12-19 06:20:10
Original
593 people have browsed it

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

Get Cookie by Specific Name

In your code, you have a getter that retrieves values from all cookies and splits them into an array. You want to modify it to retrieve values only from a specific cookie named "obligations=".

Solution:

To achieve this, you can use the following 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

Walkthrough:

  • Split the cookies string into two parts: one before and one after the name and equals sign ("; {name}=") of the desired cookie.
  • If the split resulted in two parts, it means the cookie exists.
  • Pop the second part, which contains the value and the remaining cookies string.
  • Split the remaining string by ";" to get the value of the desired cookie.
  • Shift the first part of the split result to get the actual value.

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

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