Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to declare namespace in JavaScript ?
Next article icon

How to Get Cookie by Name in JavaScript?

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Table of Content

  • Using a Simple Function to Parse Cookies
  • Using the document.cookie Property Directly and Manually Parsing
  • Using a Regular Expression to Match the Cookie Name

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:

111
output

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

111
output

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

111
output

Next Article
How to declare namespace in JavaScript ?

M

myartic07g9
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • 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 Get Browser to Navigate URL in JavaScript?
    As a web developer, you may need to navigate to a specific URL from your JavaScript code. This can be done by accessing the browser's window object and using one of the available methods for changing the current URL. In JavaScript, there are several approaches for navigating to a URL. The most commo
    4 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 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 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 URL And URL Parts In JavaScript?
    In web development, working with URLs is a common task. Whether we need to extract parts of a URL or manipulate the URL for navigation, JavaScript provides multiple approaches to access and modify URL parts. we will explore different approaches to retrieve the full URL and its various components. Th
    3 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
  • How to Set Cookies Session per Visitor in JavaScript?
    Managing session cookies in JavaScript is essential for web developers to maintain user state and preferences across multiple sessions. The document. cookie property provides a basic mechanism for cookie management, utilizing JavaScript libraries or frameworks can offer enhanced security and flexibi
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences