This post is all about getting the cookie by utilizing its name in JavaScript.
Get/Fetch Cookie by Name in JavaScript
To get the value of a cookie with a specific name in JavaScript, use the “getCookie()” function. This function takes a cookie name as a parameter and returns the value of the cookie if it exists or null if the cookie does not exist.
Example
In the given example, we will first set the cookie and then get it by name. So, first, create two buttons, “SetCookie” and “GetCookie”, in an HTML file and attach onclick events that will invoke the function on the button click:
<input type="button" class="button" value="GetCookie" onclick="getCookie()">
Define a function “setCookie()” to set the cookie on the browser using the “document.cookie” attribute:
document.cookie = "cookiename=cookie;expires=Tues, 27 Dec 2022 12:30:00 UTC";
alert("cookie is set");
}
Now, define a function called “getCookie()” by passing “name” as a parameter to get the cookie by name. Verify whether the cookie is present using the “length” attribute. If its length is not equal to zero, split the cookie string based on separator “=” and print the name and its value in an alert message:
if (document.cookie.length != 0) {
var array = document.cookie.split("=");
alert("Name=" + array[0] + " " + "Value=" + array[1]);
}
else {
alert("Cookie not available");
}
}
Call the “getCookie()” function by passing the name of the cookie as “cookiename”:
It can be observed that the cookie is first set and then its value is fetched using the cookie name:
That’s all about getting the cookie by name in JavaScript.
Conclusion
Use the “getCookie()” function by passing the “name” as a parameter, check if the cookie length is not equal to zero, split the cookie string using the “split()” method by passing a separator, and get the value of the cookie on the specified name. Note that this function will only perform its functionality if the cookie is set in the current page’s domain. This post defined the procedure for getting the cookie by name in JavaScript.