To read a value from a cookie in JavaScript, you can use the document.cookie property. The
document.cookie property contains all the cookies associated with the current document. Here's an example of how you can read a value from a cookie:
// Function to get a specific cookie value by name
function getCookie(name) {
// Split the cookie string into individual cookies
var cookies = document.cookie.split(';');
// Loop through the cookies to find the one with the specified name
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Check if this is the cookie we're looking for
if (cookie.startsWith(name + '=')) {
// Extract and return the cookie value
return cookie.substring(name.length + 1);
}
}
// Return null if the cookie is not found
return null;
}
// Example: Read a cookie named "username"
var usernameCookie = getCookie('username');
// Check if the cookie exists
if (usernameCookie) {
console.log('Username found in cookie:', usernameCookie);
} else {
console.log('Username cookie not found.');
}
In this example, the getCookie function takes a cookie name as a parameter, splits the
document.cookie string into individual cookies, and then searches for the cookie with the specified name. If found, it returns the value of that cookie. If not found, it returns
null.
Remember that cookies are stored as key-value pairs separated by semicolons. The
startsWith method is used to check if a particular cookie starts with the specified name.
Join MindStick Community
You need to log in or register to vote on answers or questions.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To read a value from a cookie in JavaScript, you can use the document.cookie property. The document.cookie property contains all the cookies associated with the current document. Here's an example of how you can read a value from a cookie:
In this example, the getCookie function takes a cookie name as a parameter, splits the document.cookie string into individual cookies, and then searches for the cookie with the specified name. If found, it returns the value of that cookie. If not found, it returns null.
Remember that cookies are stored as key-value pairs separated by semicolons. The startsWith method is used to check if a particular cookie starts with the specified name.