How to get a cookie by name in JavaScript
📅January 22, 2022
Today we will show you how to get a cookie by name in JavaScript. In the previous article, we explained how to set data in cookies using JavaScript.
Checkout more articles on JavaScript
- How to generate a Unique ID in JavaScript
- string-using-javascript" title="How to remove HTML tags from a string using JavaScript">How to remove HTML tags from a string using JavaScript
- How to split a string in JavaScript
- Execute code only after all images have been loaded in JavaScript
We will show you two different methods to get the cookie by name in JavaScript.
Method 1:
In this method, will use the Regular Expression">Regular Expression to retrieve value from the cookie by passing name.
const getCookieByName = name => (
document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || ''
)
Method 2:
Here is another method to get the cookie by name.
const getCookieByName = name => {
// Split cookie string and get all individual name=value pairs in an array
var cookieArr = document.cookie.split(";");
// Loop through the array elements
for(var i = 0; i < cookieArr.length; i++) {
var cookiePair = cookieArr[i].split("=");
/* Removing whitespace at the beginning of the cookie name
and compare it with the given string */
if(name == cookiePair[0].trim()) {
// Decode the cookie value and return
return decodeURIComponent(cookiePair[1]);
}
}
// Return null if not found
return null;
}
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂