JavaScript

Get Cookie by Name in JavaScript

Cookies are data chunks stored on a system by a web browser. They are often used to store user preferences, login information, and other types of data that can be utilized to personalize a user’s experience on a website. Cookies are typically stored as key-value pairs, where the key is a unique identifier for the cookie, and the value is the data that the cookie stores.

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="SetCookie" onclick="setCookie()">

<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:

function setCookie() {

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:

functiongetCookie(name) {
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”:

getCookie(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.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.