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

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

Susan Sarandon
Release: 2024-12-01 17:20:14
Original
585 people have browsed it

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

Cookie Retrieval by Name

In JavaScript, the retrieval of cookie values can be achieved through the document.cookie property. However, when dealing with multiple cookies, it becomes necessary to specifically target a particular cookie.

Challenge:
Modify the existing getCookie1() function to only retrieve values from a specific cookie named "obligations".

Solution:
One effective approach is to avoid iterating over an array and instead utilize a RegExp-based method:

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:

  1. Prepend a ; to the document.cookie string to ensure every cookie name is enclosed by ; =.
  2. Split the string using ; ${name}= as the separator. If the cookie name exists, it will result in an array with two strings.
  3. Obtain the string after ; ${name}= by popping the last element of the array.
  4. Split the obtained string using ; as the separator and grab the first element (using shift()) to retrieve the cookie value.

The above is the detailed content of How Can I 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