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");
In this updated code, we:
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!