
The purpose of the getcookie function in JS
13 November, 2023
38
38
0
Contributors
getcookie function is like a tool that helps a website remember things about you, like your username or preferences. It checks the small pieces of information stored by the website in your browser (these are called cookies) and gets the specific one it's looking for based on a given name. The function then returns that information so the website can use it.
// function to get a cookie value by name
function getCookie(cookieName) {
// split the cookies string into an array of 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];
// check if the cookie starts with the specified name
if (cookie.indexOf(cookieName + '=') === 0) {
// Extract and return the cookie value
return cookie.substring(cookieName.length + 1);
}
}
// if the cookie with the specified name is not found, return null
return null;
}
// xample: Set a cookie with the name "username"
document.cookie = "username=JohnDoe; expires=Thu, 01 Jan 2025 00:00:00 UTC; path=/";
// xample: Use the getCookie function to retrieve the value of the "username" cookie
var storedUsername = getCookie("username");
// Output the retrieved username
console.log("Stored username: " + storedUsername);
javascript
coding
programming
dev
webdeveloper
javascipter