How to get a cookie by name in JavaScript
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
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 to retrieve value from the cookie by passing name.
1 2 3 | const getCookieByName = name => ( document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || '' ) |
Method 2:
Here is another method to get the cookie by name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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..!! 🙂