How to Get Cookie by Name in JavaScript?
Last Updated :
29 Jul, 2024
Getting a specific name in JavaScript involves parsing the document's cookie string contains all cookies in a single string separated by semicolons and space. The goal is to extract the value of a specific cookie by the name given.
The Cookie is defined as a small piece of data that is stored on the user's computer by the web browser while browsing a website. Cookies are designed to be a reliable mechanism for websites to remember stateful information by the user's browsing activity. They can be used for various purposes such as session management, personalization, and tracking.
These are the following approaches:
Types of Cookies
We provide types of cookies for your reference.
- Session Cookies: These cookies are temporary and are deleted from the user's device when the browser is closed. They are used to store session-specific information.
- Persistent Cookies: These cookies remain on the users device for a set period until they are deleted. They are used to remember login information and settings between sessions.
- Secure Cookies: These cookies can only be transmitted over secure HTTPS connections ensuring that they are encrypted during transmission.
- HttpOnly Cookies: These cookies can not be accessed via JavaScript and can only be sent in HTTP requests.
- SameSite Cookies: These cookies include a SameSite attribute that controls whether a cookie is sent with cross origin requests providing some protection against cross site request forgery attacks.
Properties of Cookies
- Name: The name of the cookie.
- Value: The value of the cookie.
- Domain: Domain for which the cookie is valid. It can be specific domain or sub domain.
- Path : URL path for which the cookie is valid.
- Expires : The data and time when cookie will expire.
- Max Age : The maximum age of the cookie will expire.
- Secure : Indicates that cookie should only be sent over secure HTTPS connections.
- HttpOnly : Indicates that the cookie is inaccessible to JavaScript document.cookie API offering better protection against XSS attack.
- SameSite: Controls whether the cookies should be sent with cross site requests. It can have values of Strict, Lax, None
Using a Simple Function to Parse Cookies
This approach involves writing a function that splits the document.cookie string and loop through the resulting array to find the cookie with the desired name.
Syntax:
function getCookieByName(name) {
const cookies = document.cookie.split(';');
for (let cookie of cookies) {
cookie = cookie.trim();
if (cookie.startsWith(name + '=')) {
return cookie.substring(name.length + 1);
}
}
return null;
}
Example: This example shows the creation of a single function to get the cookie value.
JavaScript
document.cookie = "username=JohnDoe";
function getCookieByName(name) {
const cookies = document.cookie.split(";");
for (let cookie of cookies) {
cookie = cookie.trim();
if (cookie.startsWith(name + "=")) {
return cookie.substring(name.length + 1);
}
}
return null;
}
console.log(getCookieByName("username"));
Output:
outputUsing the document.cookie Property Directly and Manually Parsing
This method involves directly accessing document.cookie splitting it into individual cookies and iterating through them manually to find the desired cookie.
Syntax:
function getCookieByName(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(';');
for(let i=0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length,c.length);
}
return null;
}
Example: This example shows the use of document.cookie property to get the name of cookie.
JavaScript
document.cookie = "username=GeeksForGeeks";
function getCookieByName(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(';');
for(let i=0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length,c.length);
}
return null;
}
console.log(getCookieByName("username"));
Output:
outputUsing a Regular Expression to Match the Cookie Name
This approach users a regular expression to search for the cookie name and extract its vale.
Syntax:
function getCookieByName(name) {
const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
if (match) return match[2];
return null;
}
Example: This example shows the use of regular expression to get the value of cookie.
JavaScript
document.cookie = "username=GFG";
function getCookieByName(name) {
const match = document.cookie
.match(new RegExp("(^| )" + name + "=([^;]+)"));
if (match) return match[2];
return null;
}
console.log(getCookieByName("username"));
Output:
output
Similar Reads
How To Get Element By Class Name In JavaScript ?
When working with the DOM in JavaScript, selecting elements by their class names is a common task. JavaScript provides several methods to achieve this, whether we need to select one or multiple elements. In this article, we will cover different approaches to get elements by class name in JavaScript.
3 min read
How to Get Domain Name From URL in JavaScript?
In JavaScript, the URL object allows you to easily parse URLs and access their components. This is useful when you need to extract specific parts of a URL, such as the domain name. The hostname property of the URL object provides the domain name of the URL. PrerequisiteJavascriptHTMLBelow are the fo
2 min read
How to declare namespace in JavaScript ?
The coding standard of assigning scope to identifiers (names of types, functions, variables, and so on) to avoid conflicts between them is known as a namespace. It is a framework for a collection of identifiers, functions, and methods. It gives its contents a sense of direction so that they are easi
3 min read
How to Get Value by Class Name using JavaScript ?
This article will show you how to use JavaScript to get value by class name. To get the value of an element by its class name in JavaScript, you can use the getElementsByClassName() method. This method returns an array-like object of all elements with the specified class name. You can then access th
2 min read
How to set up a cookie that never expires in JavaScript ?
We can set up a cookie that never expires in JavaScript using the following approach: Prerequisites : Intermediate level knowledge of JavaScriptBasic HTML Disclaimer: All the cookies expire as per the cookie specification. So, there is no block of code you can write in JavaScript to set up a cookie
3 min read
How to get the Class Name of an Object in JavaScript
In this article, we will learn how we can get the class Name of an Object with multiple approaches in JavaScript. In JavaScript, determining an object's class name can be done using multiple approaches. The constructor property of an object reveals the function that created it, while the instanceof
3 min read
How to get the Value by a Key in JavaScript Map?
JavaScript Map is a powerful data structure that provides a convenient way to store key-value pairs and retrieve values based on keys. This can be especially useful when we need to associate specific data with unique identifiers or keys. Different Approaches to Get the Value by a Key in JavaScript M
3 min read
How to access history in JavaScript ?
In this article, we will learn how to access history in JavaScript. We will use the History object to access the history stack in JavaScript. Every web browser will store the data on which websites or webpages opened during the session in a history stack. To access this history stack we need to use
3 min read
How to create cookie with the help of JavaScript ?
A cookie is an important tool as it allows you to store the user information as a name-value pair separated by a semi-colon in a string format. If we save a cookie in our browser then we can log in directly to the browser because it saves the user information. Approach: When a user sends the request
2 min read
How to get client IP address using JavaScript?
Imagine your computer as your apartment. Just like each apartment has a unique address for receiving mail, your computer has an IP address that helps it receive information from the internet. This IP address acts like a label that identifies your specific device on the vast network of computers, ens
2 min read