Get cookie by name

jquery get cookie by name
javascript get all cookies
javascript get cookie domain
jquery cookie
javascript delete cookie
get cookie php
getcookie is not defined
document.cookie not working

I have a getter to get the value from a cookie.

Now I have 2 cookies by the name shares= and by the name obligations= .

I want to make this getter only to get the values from the obligations cookie.

How do I do this? So the for splits the data into separate values and puts it in an array.

 function getCookie1() {
    // What do I have to add here to look only in the "obligations=" cookie? 
    // Because now it searches all the cookies.

    var elements = document.cookie.split('=');
    var obligations= elements[1].split('%');
    for (var i = 0; i < obligations.length - 1; i++) {
        var tmp = obligations[i].split('$');
        addProduct1(tmp[0], tmp[1], tmp[2], tmp[3]);

One approach, which avoids iterating over an array, would be:

function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();


Splitting a string by token will produce either, an array with one string (same value), in case token does not exist in a string, or an array with two strings , in case token is found in a string .

The first (left) element is string of what was before the token, and the second one (right) is what is string of what was after the token.

(NOTE: in case string starts with a token, first element is an empty string)

Considering that cookies are stored as follows:

"{name}={value}; {name}={value}; ..."

in order to retrieve specific cookie value, we just need to get string that is after "; {name}=" and before next ";". Before we do any processing, we prepend the cookies string with "; ", so that every cookie name, including the first one, is enclosed with "; " and "=":

"; {name}={value}; {name}={value}; ..."

Now, we can first split by "; {name}=", and if token is found in a cookie string (i.e. we have two elements), we will end up with second element being a string that begins with our cookie value. Then we pull that out from an array (i.e. pop), and repeat the same process, but now with ";" as a token, but this time pulling out the left string (i.e. shift) to get the actual token value.

Get cookie by name, One approach, which avoids iterating over an array, would be: function getCookie(name) { const value = `; ${document.cookie}`; const parts = value.split​(`;  Yoy can get any cookie by name using only JS. The code is also cleaner IMHO (except for the long line, that I'm sure you can easily fix).

I would prefer using a single regular expression match on the cookie:

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

OR Also we are able to use as a function , check below code.

function check_cookie_name(name) 
      var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
      if (match) {
           console.log('--something went wrong---');

Improved thanks to Scott Jungwirth in the comments.

cookies.get(), The get() method of the cookies API retrieves information about a single cookie, given its name and URL. On clicking Get Cookie button, the below dialog box appears. Here, we can see that only a single name-value is displayed. However, if you click, Get Cookie without filling the form, the below dialog box appears. Example 2

use a cookie getting script:

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var 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;

then call it:

var value = readCookie('obligations');

i stole the code above from quirksmode cookies page. you should read it.

Document.cookie, cookie property. This property represents all the cookies associated with a document. To create or store a new cookie, assign a name=value string to this  The parameters of the function above are the name of the cookie (cname), the value of the cookie (cvalue), and the number of days until the cookie should expire (exdays). The function sets a cookie by adding together the cookiename, the cookie value, and the expires string.

If you use jQuery I recommend you to use this plugin:

<script type="text/javascript"

So you can read cookie like this:

var value = $.cookie("obligations");

Also you can write cookie:

$.cookie('obligations', 'new_value');
$.cookie('obligations', 'new_value', { expires: 14, path: '/' });

Delete cookie:


Set and Get Cookies in JavaScript, Use the following three functions for working with cookies. function getCookie(​name) {. var v = document. get the cookie value by name if a cookie name exists. - getcookiebyname.js

The methods in some of the other answers that use a regular expression do not cover all cases, particularly:

  1. When the cookie is the last cookie. In this case there will not be a semicolon after the cookie value.
  2. When another cookie name ends with the name being looked up. For example, you are looking for the cookie named "one", and there is a cookie named "done".
  3. When the cookie name includes characters that are not interpreted as themselves when used in a regular expression unless they are preceded by a backslash.

The following method handles these cases:

function getCookie(name) {
    function escape(s) { return s.replace(/([.*+?\^${}()|\[\]\/\\])/g, '\\$1'); };
    var match = document.cookie.match(RegExp('(?:^|;\\s*)' + escape(name) + '=([^;]*)'));
    return match ? match[1] : null;

This will return null if the cookie is not found. It will return an empty string if the value of the cookie is empty.


  1. This function assumes cookie names are case sensitive.
  2. document.cookie - When this appears on the right-hand side of an assignment, it represents a string containing a semicolon-separated list of cookies, which in turn are name=value pairs. There appears to be a single space after each semicolon.
  3. String.prototype.match() - Returns null when no match is found. Returns an array when a match is found, and the element at index [1] is the value of the first matching group.

Regular Expression Notes:

  1. (?:xxxx) - forms a non-matching group.
  2. ^ - matches the start of the string.
  3. | - separates alternative patterns for the group.
  4. ;\\s* - matches one semi-colon followed by zero or more whitespace characters.
  5. = - matches one equal sign.
  6. (xxxx) - forms a matching group.
  7. [^;]* - matches zero or more characters other than a semi-colon. This means it will match characters up to, but not including, a semi-colon or to the end of the string.

Set cookie, get cookie and delete cookie, header. function getCookie(name) { var re = new RegExp(name + "=([^;]+)"); var value = re.exec(document.cookie);  document.cookie = "name=" + encodeURIComponent("Christopher Columbus"); By default, the lifetime of a cookie is the current browser session, which means it is lost when the user exits the browser. For a cookie to persist beyond the current browser session, you will need to specify its lifetime (in seconds) with a max-age attribute.

Retrieving values from Cookies < JavaScript, get cookie by name without using a regular expression. */. var getCookie = function(name) {. var getCookieValues = function(cookie) {. document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();} function deleteCookie(name) { setCookie(name, '', -1); } All three functions are optimized on size. You may squeeze out some more bytes by minification. Warning: According to HTTP Cookie specs, semi-colons, commas, equals signs, and white spaces are not allowed characters. If you do need to use them, you will need to write a custom encode and decode function.

get the cookie value by name if a cookie name exists. · GitHub, getCookie.ts. // Given a cookie key `name`, returns the value of. // the cookie or `​null`, if the key is not found. function getCookie(name: string): string {. hope this one could help you to get name and value of your cookie ${cookie['cookiename'].getName()} ${cookie['cookiename'].getValue()} OR ${cookie.cookiename.getName()} ${cookie.cookiename.getValue()} OR ${cookie.<cookiename>.name} ${cookie.<cookiename>.value}

Get a cookie by name in TypeScript · GitHub, Docs > Client API Reference > DevExpress.Web Scripts > ASPxClientUtils > Methods > GetCookie(name). All docs. V20.1  FormsAuthentication.Decrypt takes the actual value of the cookie, not the name of it. You can get the cookie value like. HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value; and decrypt that.

  • is there some resin your not just making it an array?
  • making the cookie an array I should say.
  • No, how could I do that?
  • Possible duplicate of What is the shortest function for reading a cookie by name in JavaScript?
  • You might want to accept an answer: you question is still tagged as unanswered.
  • @user3132564 tried to edit this in, but its actually a comment: This method returns the wrong value when you search for a suffix of a cookie - if the value of document.cookie is "FirstName=John" and you call getCookie("Name"), you'll get back "John" even though there's no cookie by that name. It also doesn't work if one cookie's name is the suffix of another - if document.cookie is "Name=John; LastName=Doe", calling split("Name=") returns an array with three strings and the method doesn't return the right value for getCookie("Name").
  • Warning about implementation in this answer: if there is more than one cookie by the same name then no cookie value will be returned. For example, if there's a cookie named stackToken set for domains as well as then if you call getCookie("stackToken") neither value will be returned -- parts.length will be greater than 2. If you know all cookie values for the same name (but different domain and path) will be the same, see accepted answer here:…
  • @DennisJaheruddin - Looks like the suffix issue was fixed.
  • @NathanJ.Brauer you're correct. Updated to address that issue long time ago, but made a note only in changelog, instead of in comments.
  • there is a fault of it. If the cookie "name" and underlined in another like name, IE 10+ also gives an error. Eg: "user" : "Joe", "user_name" : "Doe"
  • This can have false matches if two cookies have the same suffix. It will match both xyz=value and abcxyz=value when name = xyz.
  • unescape((document.cookie.match(key + '=([^;].+?)(;|$)') || [])[1] || ''); Modified version of Glize/dom/Cookies
  • update Regex to new RegExp('(^| )' + name + '=([^;]+)') to avoid issue raised by @BrentWashburne. Also I made a jsperf test for this and the answer with the highest votes, this one comes out slightly on top, but is definitely less code and easier to follow:
  • @ScottJungwirth Yes, but then you must update the return statement to return match[2];