In the context of HTTP cookies, a “cookie with multiple names” typically refers to a scenario where a single cookie string contains multiple key-value pairs representing different cookies. Each key-value pair in the string represents a separate cookie, with each cookie having its own name and value.
Format of Cookies with Multiple Names:
- Cookies with multiple names are represented as a single string containing multiple key-value pairs separated by semicolons (
;). - Each key-value pair represents a separate cookie, with the cookie’s name and value separated by an equals sign (
=).
document.cookie = "username=John Doe;
language=en;
sessionid=abc123";
Explanation:
- In the example above, a single cookie string is being set with three separate cookies:
username,language, andsessionid. - Each cookie is represented by a key-value pair within the string, with the cookie’s name (
username,language,sessionid) followed by an equals sign (=) and its corresponding value (John Doe,en,abc123).
Reading Cookies with Multiple Names:
- To read cookies with multiple names, you can access the
document.cookieproperty, which returns a string containing all cookies associated with the current document. - You can then parse the cookie string to extract individual cookies and their respective names and values.
let cookieString = document.cookie;
let cookies = cookieString.split("; ");
for (let cookie of cookies) {
let [name, value] = cookie.split("=");
console.log(`Cookie Name: ${name},
Value: ${value}`);
}