How to Get a Cookie by Name in JavaScript

Waqar Aslam Feb 02, 2024
How to Get a Cookie by Name in JavaScript

Cookies are pieces of information that are kept on your computer in the form of very tiny text files. When a web server has finished sending a web page to a browser, the connection between the two is severed, and the server promptly forgets any information on the user.

Cookies were first developed as a solution to the question of How to remember information about the user for the following reasons.

  1. A user’s name can be saved in a cookie whenever that person visits a particular website.
  2. When the user returns to the website later, the cookie will “remember” their name.

The first thing we will do is construct a function, which we will call getACookie, and we will use cookieName as the method’s argument.

Next, we will create a variable that we will refer to as nameOfCookie and fill it with the text that will search for cookieName + '='.

let nameOfCookie = cookieName + '=';

Now that we have created a new variable with the name cookieDecoded, we will decode the cookie string using the decodeURIComponent property.

Previously, we had used document.cookie to retrieve all of the cookies to process any special characters, such as $, but now we will use this new variable instead.

Through the use of the Document property cookie, it is possible to read and write cookies that are connected with the document. It is a getter and setter for the actual values of the cookies that are being stored.

let cookieDecoded = decodeURIComponent(document.cookie);

Make a new variable called cookieArray that will hold the array produced after we used the .split(';') property to separate the cookie into an array at the ; character.

let cookieArray = cookieDecoded.split(';');

Moving further, we shall iterate through the cookieArray.

for (let i = 0; i < cookieArray.length; i++) ```

Inside the loop, we will create a new variable that we will refer to as `cIndex`. This variable will hold the value of the specific index of `cookieArray` that the value of `i` will determine.

```javascript
let cIndex = cookieArray[i];

The charAt() attribute will initiate a while loop that will examine the value of the character located at index 0 of the cIndex array to determine whether or not it is empty.

while (cIndex.charAt(0) == ' ') ```

If the first index of `cIndex` is empty, then the value at the second index will be stored in the `cIndex` variable by using the `subString()` property.

```javascript
cIndex = cIndex.substring(1);

If the value we receive from the expression cIndex.indexOf(nameOfCookie) is equal to zero, then our condition will be met, and we will return the value obtained from cIndex.

if (cIndex.indexOf(nameOfCookie) == 0) ```

<!--adsense-->

If the condition evaluates to `true`, then we will return the value of the cookie, which is represented by the `c.substring function (name.length, c.length)`. Also, if the condition turns out to be `false`, we will return an empty string.

```javascript
{ return cIndex.substring(nameOfCookie.length, cIndex.length); }
return '';

Full Source Code:

function getACookie(cookieName) {
  let nameOfCookie = cookieName + '=';
  let cookieDecoded = decodeURIComponent(document.cookie);
  let cookieArray = cookieDecoded.split(';');

  for (let i = 0; i < cookieArray.length; i++) {
    let cIndex = cookieArray[i];
    while (cIndex.charAt(0) == ' ') {
      cIndex = cIndex.substring(1);
    }
    if (cIndex.indexOf(nameOfCookie) == 0) {
      return cIndex.substring(nameOfCookie.length, cIndex.length);
    }
  }
  return '';
}
Author: Waqar Aslam
Waqar Aslam avatar Waqar Aslam avatar

I am Waqar having 5+ years of software engineering experience. I have been in the industry as a javascript web and mobile developer for 3 years working with multiple frameworks such as nodejs, react js, react native, Ionic, and angular js. After which I Switched to flutter mobile development. I have 2 years of experience building android and ios apps with flutter. For the backend, I have experience with rest APIs, Aws, and firebase. I have also written articles related to problem-solving and best practices in C, C++, Javascript, C#, and power shell.

LinkedIn

Related Article - JavaScript Cookies