---
title: "Read a Value from cookie in JavaScript"  
description: "Read a Value from cookie in JavaScript"  
author: "Anonymous User"  
published: 2021-07-19  
updated: 2023-11-29  
canonical: https://www.mindstick.com/forum/156524/read-a-value-from-cookie-in-javascript  
category: "javascript"  
tags: ["javascript"]  
reading_time: 2 minutes  

---

# Read a Value from cookie in JavaScript

How do I create and read a [value](https://www.mindstick.com/articles/23219/an-optimized-description-adds-value-to-experience-and-in-turn-effectively-guest-posting-packages) from [cookie](https://www.mindstick.com/blog/123/what-is-cookie-poisoning) in [JavaScript](https://www.mindstick.com/articles/874/how-to-create-watermark-text-for-textbox-by-using-javascript)?

## Replies

### Reply by Aryan Kumar

To read a value from a cookie in JavaScript, you can use the **document.cookie** property. The **document.cookie** property contains all the cookies associated with the current document. Here's an example of how you can read a value from a cookie:

```plaintext
// Function to get a specific cookie value by name
function getCookie(name) {
    // Split the cookie string into individual cookies
    var cookies = document.cookie.split(';');

    // Loop through the cookies to find the one with the specified name
    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i].trim();

        // Check if this is the cookie we're looking for
        if (cookie.startsWith(name + '=')) {
            // Extract and return the cookie value
            return cookie.substring(name.length + 1);
        }
    }

    // Return null if the cookie is not found
    return null;
}

// Example: Read a cookie named "username"
var usernameCookie = getCookie('username');

// Check if the cookie exists
if (usernameCookie) {
    console.log('Username found in cookie:', usernameCookie);
} else {
    console.log('Username cookie not found.');
}
```

In this example, the **getCookie** function takes a cookie name as a parameter, splits the **document.cookie** string into individual cookies, and then searches for the cookie with the specified name. If found, it returns the value of that cookie. If not found, it returns **null**.

Remember that cookies are stored as key-value pairs separated by semicolons. The **startsWith** method is used to check if a particular cookie starts with the specified name.


---

Original Source: https://www.mindstick.com/forum/156524/read-a-value-from-cookie-in-javascript

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
