Reading and Parsing Cookies
You'll learn how to read the browser's cookie string and extract individual cookie values using JavaScript.
The Core Idea
While setting cookies with document.cookie appends values one at a time, reading cookies gives you everything at once as a single string. When you access document.cookie, the browser returns all cookies for the current domain in one long format like this:
"username=John; theme=dark; sessionId=abc123"
Your job is to parse this string to find the specific cookie you need.
Reading the Cookie String
Simply access document.cookie to get all cookies:
const allCookies = document.cookie;
console.log(allCookies);
// "username=John; theme=dark; sessionId=abc123"
Parsing Individual Cookies
To extract a specific cookie value, you need to:
- Split the string by
"; "(semicolon and space) to get individual cookies - Loop through each cookie
- Split each cookie by
"="to separate name from value - Find the one you want
function getCookie(name) {
const cookies = document.cookie.split('; ');
for (let cookie of cookies) {
const [cookieName, cookieValue] = cookie.split('=');
if (cookieName === name) {
return cookieValue;
}
}
return null; // Cookie not found
}
const username = getCookie('username');
console.log(username); // "John"
Think of It Like a Bulletin Board
Imagine document.cookie as reading all the notes on a bulletin board at once. You get one long string of all messages, and you need to manually separate and identify each note to find the one you're looking for.
Key Takeaway: document.cookie returns all cookies as one semicolon-separated string; you must split and parse it to extract individual cookie values by name.