get cookie by name in javascript

How to Get Cookie By Name in JavaScript

JavaScript cookies allow you to persist information between client-side and server-side. Generally, it contains information stored as key-value pairs separated by semi-colon (;). Cookies are read and written to when a visitor visits your web page, by the JavaScript on that web page. Typically, all cookies are concatenated together into a single string. But often you may need to get cookie by name in JavaScript, and traversing the entire string for this purpose can be tedious. In this article, we will learn how to get cookie by name in JavaScript.

How to Get Cookie By Name in JavaScript

Typically, web developers split the cookie string by semi colon into array of key-value strings. Then they iterate through the array searching for the cookie by name.

We will use a similar but more efficient approach. Here is a function to get cookie by name from cookie string.

function get_cookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
}

Let us look at the above code in detail. We have defined a function that accepts cookie name as input. A web page’s cookie string is stored in document.cookie variable that is available by default in every browser, for every web page.

We will store its value in a variable, and prefix it with a semicolon.

We split this string using token ‘;name=’ where name is the cookie name we are looking for. If the cookie name is present in our cookie string, it will be split in two parts, else only 1 part. The first part is the part before the token and the second part is the part after the token. If the first element itself is required cookie, then the first part of the split is an empty array while the second one contains the cookie.

If the cookie is present in cookie string, the second part of split will start with ‘;name=’. In this case, we repeat the above process on the second part of the split string, that contains ‘name=value’ for our cookie. We use pop() method to retrieve the second array element. Then we split the string using semi-colon(;). Here too, the second element of result will contain the cookie. Finally, we use shift() method to remove 1st element of split result array.

In this case, please note, if your cookie string contains two cookies with same name, then none will be returned since it depends on the condition that initial split() method results in 2 parts and not more. If you have two cookies with same name, you will end up with more than 2 parts. In such cases, you can modify the (parts.length == 2) condition accordingly.

Alternatively, you can also use regular expression to look for cookies with specific names, as shown below.

window.getCookie = function(name) {
  var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
  if (match) return match[2];
}

In the above code, we simply use match() function to look for a regular expression that matches ‘name=value’ in document.cookie string. If a match is found, then we return it.

In this article, we have learnt how to get cookie by name in JavaScript. You can customize it as per your requirements.

Also read:

How to Find Max Value of Attribute in Array of JS Objects
How to Get Last Item in JS Array
How to Check if Variable is Object in JS
How to Check if Browser Tab is Active in JS
How to Find DOM Element Using Attribute Value in JS

Leave a Reply

Your email address will not be published. Required fields are marked *