555

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]);
    }
 }
Neuron
  • 5,141
  • 5
  • 38
  • 59

48 Answers48

694

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

function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
}

Walkthrough

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.

Arseniy-II
  • 8,323
  • 5
  • 24
  • 49
kirlich
  • 7,998
  • 2
  • 19
  • 10
  • 20
    @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"). – Dennis Jaheruddin Dec 24 '13 at 13:08
  • 26
    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 .stackexchange.com as well as programmers.stackexchange.com 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: http://stackoverflow.com/questions/5639346/shortest-function-for-reading-a-cookie-in-javascript?rq=1 – jlpp Apr 25 '14 at 18:15
  • 8
    @DennisJaheruddin - Looks like the suffix issue was fixed. – Nathan J.B. Jul 13 '15 at 18:11
  • 2
    @NathanJ.Brauer you're correct. Updated to address that issue long time ago, but made a note only in changelog, instead of in comments. – kirlich Nov 19 '15 at 19:36
  • 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"` – BOZ Mar 28 '19 at 21:32
  • 1
    As for perfomance: I set up a jsperf test for the offered solutions: https://jsperf.com/getcookie-performance . Performance strongly differs between browsers. – sborn Oct 16 '19 at 14:31
  • Warning: this breaks in older browsers, like IE11. – deweydb May 13 '21 at 15:12
  • It's 2023, is there still not a "built in" way to do this? – Sammy Taylor Jun 16 '23 at 18:49
242

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(match[2]);
      }
      else{
           console.log('--something went wrong---');
      }
   }

Improved thanks to Scott Jungwirth in the comments.

Manish sharma
  • 838
  • 2
  • 8
  • 24
Jonathan Camenisch
  • 3,472
  • 1
  • 20
  • 9
  • 12
    This can have false matches if two cookies have the same suffix. It will match both `xyz=value` and `abcxyz=value` when `name = xyz`. – Brent Washburne Oct 19 '15 at 18:39
  • 3
    `unescape((document.cookie.match(key + '=([^;].+?)(;|$)') || [])[1] || '');` Modified version of [Glize/dom/Cookies](https://github.com/Datamart/Glize/blob/master/src/dom/Cookies.js#L33) – Valentin Podkamennyi Oct 20 '15 at 17:21
  • 25
    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: http://jsperf.com/simple-get-cookie-by-name – Scott Jungwirth Jan 07 '16 at 01:13
  • 5
    @ScottJungwirth Yes, but then you must update the return statement to return match[2]; – Joe May 12 '17 at 22:38
  • @ScottJungwirth Why not `new RegExp('(^|;)' + name + '=([^;]+)')`? The `name` behind the start of a line or semicolon, why a space ` `? – junlin Apr 26 '19 at 14:22
  • Is there a reason not to change the first group `'(^| )'` to a non-capturing group `'(?:^| )'`? Then the array would be smaller and the match found at index `1`. – CyberMoai Mar 10 '21 at 19:00
  • 1
    Here is this answer rewritten as an ES6 one liner: `const getCookie = name => document.cookie.match(new RegExp(\`(^| )${name}=([^;]+)\`))?.at(2);` It returns undefined if the cookie doesn't exist. – tsgrgo Aug 31 '22 at 08:43
77

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.

Notes:

  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.
John S
  • 21,212
  • 8
  • 46
  • 56
  • 5
    This answer is the best and shortest function that works in all cases without false matches. It also has the best explanation of how it works. However, the **escape** function is not explained and I would think that if the author created the cookie he would know if the name needed to be escaped or not. So I would rather see a shorter function: `function getCookie(name) { var match = document.cookie.match(RegExp('(?:^|;\\s*)' + name + '=([^;]*)')); return match ? match[1] : null; }` – Jeff Baker Dec 23 '15 at 21:12
  • 1
    If it's to be a generic tool, it should either escape the name or throw an error if the name can't be embedded directly in regex. People who know the constraints of their application can remove the escape or the guard. – Joe Lapp Jul 19 '16 at 16:12
64

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

https://github.com/carhartl/jquery-cookie
https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js

<script type="text/javascript"
 src="//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js">

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:

$.removeCookie('obligations');
trante
  • 33,518
  • 47
  • 192
  • 272
  • 1
    Not sure why this hasn't been voted the best answer really. Yes its jQuery and not javascript but at the same time IT IS!!!! – Cozzbie Nov 03 '14 at 08:32
  • 33
    @Cozzbie probably to include an external library(thereby adding another http request) to just fetch a cookie value is kind of an unnecessary overkill. – rahulserver Oct 02 '15 at 12:28
  • I am getting an error "Uncaught ReferenceError: $ is not defined" at "$.cookie". Though I included all the necessary libraries like jquery.min.js and the library suggested in this answer. – Adarsh Singh May 07 '20 at 11:56
  • @rahulserver Yes, may be 2015, but now, 2021 it really doesn't matter and before I start to implement all of the regular expression functions I include the script and I am done. – Peter VARGA Jan 28 '21 at 11:16
  • 1
    For what it's worth, `jquery-cookie` has been superseded by `js-cookie`: https://github.com/js-cookie/js-cookie – Brylie Christopher Oxley Dec 03 '21 at 09:18
58

Here is a one liner to get a cookie value with a specific name without the need of any external lib:

const value = ('; '+document.cookie).split(`; COOKIE_NAME=`).pop().split(';')[0];

This answer is based on kirlich's brilliant solution. The only compromise of this solution is, that you will get an empty string when the cookie does not exist. In most cases this should not be a deal breaker, though.

Martin Braun
  • 10,906
  • 9
  • 64
  • 105
42

4 years later, ES6 way simpler version.

function getCookie(name) {
  let cookie = {};
  document.cookie.split(';').forEach(function(el) {
    let [k,v] = el.split('=');
    cookie[k.trim()] = v;
  })
  return cookie[name];
}

I have also created a gist to use it as a Cookie object. e.g., Cookie.set(name,value) and Cookie.get(name)

This read all cookies instead of scanning through. It's ok for small number of cookies.

allenhwkim
  • 27,270
  • 18
  • 89
  • 122
32

One liner to convert cookie into JavaScript Object or Map

Object.fromEntries(document.cookie.split('; ').map(v=>v.split(/=(.*)/s).map(decodeURIComponent)))
new Map(document.cookie.split('; ').map(v=>v.split(/=(.*)/s).map(decodeURIComponent)))
nkitku
  • 4,779
  • 1
  • 31
  • 27
25

I have modified the function that Jonathan provided here, by using regular expression you can get a cookie value by its name like this:

function getCookie(name){
    var pattern = RegExp(name + "=.[^;]*")
    var matched = document.cookie.match(pattern)
    if(matched){
        var cookie = matched[0].split('=')
        return cookie[1]
    }
    return false
}

If it returns empty string it means that the cookie exists but has no value, if it returns false then the cookie doesn't exist. I hope this helps.

Mohyaddin Alaoddin
  • 2,465
  • 1
  • 19
  • 14
23

You can use js-cookie library to get and set JavaScript cookies.

Include to your HTML:

<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>

To create a Cookie:

Cookies.set('name', 'value');

To read a Cookie:

Cookies.get('name'); // => 'value'
Lanil Marasinghe
  • 2,785
  • 24
  • 24
23

A simple way :)

const cookieObj = new URLSearchParams(document.cookie.replaceAll("&", "%26").replaceAll("; ","&"))
cookieObj.get("your-cookie-name")
ryanm
  • 2,239
  • 21
  • 31
elad gasner
  • 655
  • 7
  • 7
  • 2
    but cookies keys or value can have '&' eg: name=A&T or date&time=any-date, then it will parse it wrong – nkitku Apr 19 '22 at 05:37
  • 1
    @nkitku I built something similar to this, then found this answer and glad you mentioned the "&" character issue. Good catch! I've modified the code above to work around this problem; I have tested this solution as well. – ryanm Aug 02 '22 at 19:20
  • 1
    but it converts '+' (plus) to space eg: x=car+bike will give "car bike" [test here](https://www.typescriptlang.org/play?target=99&jsx=0#code/MYewdgziA2CmB00QHMAUATEwCuBbWYALvKCANYCWsAlANwBQmO+RJI5VABALycAGAD27AAhgCcA1ACMKZWLVgCADhTGwI3ACQBvMLADunACIjCsVCbPwwIfamqcJnAKwAGd9XiEQAVQAqAMIAyoRiFGBo1AC+tEqmABbcAPR8DKCQhJwCPJx6hj4ASgAyQbDiwPEACuIiuBAYWHgExKSUCGpK0CLAsACC0NCoAEQAZEMANJxDAKQATABsQ54dXT39g0O0U5OjS3T06VBwiCioAvDIsISoAOQCN9TUQA) – nkitku Oct 07 '22 at 10:22
14

My one linear function to get the value cookie by its key.

cookie = key=>((new RegExp((key || '=')+'=(.*?); ','gm')).exec(document.cookie+'; ') ||['',null])[1]

Call cookie function as

cookie('some-key')
varun sharma
  • 1,017
  • 15
  • 19
13

Here is a pretty short version

 function getCookie(n) {
    let a = `; ${document.cookie}`.match(`;\\s*${n}=([^;]+)`);
    return a ? a[1] : '';
}

Note that I made use of ES6's template strings to compose the regex expression.

mfalade
  • 1,647
  • 2
  • 17
  • 16
12

I know it is an old question but I came across this problem too. Just for the record, There is a little API in developers mozilla web page.

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).

function getCookie(sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
}

As stated in the comments be aware that this method assumes that the key and value were encoded using encodeURIComponent(). Remove decode & encodeURIComponent() if the key and value of the cookie were not encoded.

Marc
  • 246
  • 3
  • 10
  • 1
    Just be aware that method assumes the cookie name and value were both encoded using `encodeURIComponent()` when the cookie was set, which will be true if you use the companion function to set the cookie, but might not always be the case. [test](http://jsfiddle.net/sr20zmq1/1/) – John S Nov 10 '14 at 15:18
  • @JohnS We could just remove the decodeURIComponent though, right? (If we didn't use it to set the cookie?) Would it still work? – NiCk Newman Mar 29 '15 at 00:06
  • Yep, just removed the decodeURI and this regexp is a monster. Thank you Marc, voted! – NiCk Newman Mar 29 '15 at 00:16
11
function getCookie(name) {
    var pair = document.cookie.split('; ').find(x => x.startsWith(name+'='));
    if (pair)
       return pair.split('=')[1]
}
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
alpav
  • 2,972
  • 3
  • 37
  • 47
  • `find` already returns undefined if nothing is found. This can be simplified by adding `.replace(/.*=/, '')` and removing the if statement and split. – DoYouEvenCodeBro Nov 28 '21 at 22:26
  • ["Nice and simple. But one gets in trouble if the cookie contains an '='"](https://stackoverflow.com/questions/10730362/get-cookie-by-name#comment117027227_49224652) – Leponzo Feb 27 '22 at 19:22
  • `return pair.substring(pair.indexOf("=") + 1); // takes care of the case where the value also contains "="` – Leponzo Feb 27 '22 at 19:33
8

kirlich gave a good solution. However, it fails when there are two cookie values with similar names, here is a simple fix for this situation:

function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length >= 2) return parts.pop().split(";").shift();
}
zaaath
  • 737
  • 9
  • 17
7

It seems to me you could split the cookie key-value pairs into an array and base your search on that:

var obligations = getCookieData("obligations");

Which runs the following:

function getCookieData( name ) {
    var pairs = document.cookie.split("; "),
        count = pairs.length, parts; 
    while ( count-- ) {
        parts = pairs[count].split("=");
        if ( parts[0] === name )
            return parts[1];
    }
    return false;
}

Fiddle: http://jsfiddle.net/qFmPc/

Or possibly even the following:

function getCookieData( name ) {
    var patrn = new RegExp( "^" + name + "=(.*?);" ),
        patr2 = new RegExp( " " + name + "=(.*?);" );
    if ( match = (document.cookie.match(patrn) || document.cookie.match(patr2)) )
        return match[1];
    return false;
}
Sampson
  • 265,109
  • 74
  • 539
  • 565
  • 1
    is there a method to use document.cookie.indexOf(name) and to compare? –  May 24 '12 at 02:59
  • @AndrejHefner You could, though that would match substrings. So if you had a cookie name "foobar", and one named "bar", you may get confuse the "bar" in "foobar" with the key "bar". – Sampson May 24 '12 at 03:13
  • @AndrejHefner Please see the later method, which should be faster, since it checks the string for a match. – Sampson May 24 '12 at 03:29
  • 1
    The second method has a bug in which it won't find the last cookie value since it always looks for a ; at the end. A correction version would be: `function getCookieData( name ) { var patrn = new RegExp( "(?:^| )" + name + "=(.*?)(?:;|$)" ); if ( match = (document.cookie.match(patrn) )) return match[1]; return false; } ` – Oz Solomon Nov 12 '13 at 19:25
7

Use object.defineProperty

With this, you can easily access cookies

Object.defineProperty(window, "Cookies", {
    get: function() {
        return document.cookie.split(';').reduce(function(cookies, cookie) {
            cookies[cookie.split("=")[0]] = unescape(cookie.split("=")[1]);
            return cookies
        }, {});
    }
});

From now on you can just do:

alert( Cookies.obligations );

This will automatically update too, so if you change a cookie, the Cookies will change too.

Downgoat
  • 13,771
  • 5
  • 46
  • 69
  • 3
    Perfect! except that it will not work for objects that have some characters like dashes (as cookie names), and when splitting, objects have a blank space on first so I go `cookies[(cookie.split("=")[0]).replace(/ /g,'')] = ..`. Thanks!! – Ismail Jul 17 '16 at 14:55
  • @Samuel Elh correct, but you also can use .trim() instead of replace(/ /g, '' ) – mtizziani Jan 15 '17 at 06:54
6

In my projects I use following function to access cookies by name

function getCookie(cookie) {
    return document.cookie.split(';').reduce(function(prev, c) {
        var arr = c.split('=');
        return (arr[0].trim() === cookie) ? arr[1] : prev;
    }, undefined);
}
Eugene Burtsev
  • 1,465
  • 4
  • 24
  • 45
6

always works well:

function getCookie(cname) {
    var name = cname + "=",
        ca = document.cookie.split(';'),
        i,
        c,
        ca_length = ca.length;
    for (i = 0; i < ca_length; i += 1) {
        c = ca[i];
        while (c.charAt(0) === ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) !== -1) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function setCookie(variable, value, expires_seconds) {
    var d = new Date();
    d = new Date(d.getTime() + 1000 * expires_seconds);
    document.cookie = variable + '=' + value + '; expires=' + d.toGMTString() + ';';
}

No requirements for jQuery or anything. Pure old good JavaScript.

Lukas Liesis
  • 24,652
  • 10
  • 111
  • 109
6

Simple function for Get cookie with cookie name:

function getCookie(cn) {
    var name = cn+"=";
    var allCookie = decodeURIComponent(document.cookie).split(';');
    var cval = [];
    for(var i=0; i < allCookie.length; i++) {
        if (allCookie[i].trim().indexOf(name) == 0) {
            cval = allCookie[i].trim().split("=");
        }   
    }
    return (cval.length > 0) ? cval[1] : "";
}
Saddam H
  • 139
  • 2
  • 4
6

Apparently MDN has never heard of the word-boundary regex character class \b, which matches contiguous \w+ that is bounded on either side with \W+:

getCookie = function(name) {
    var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
    return r ? r[1] : null;
};

var obligations = getCookie('obligations');
cowbert
  • 3,212
  • 2
  • 25
  • 34
3

set by javascript

document.cookie = 'cookiename=tesing';

get by jquery with the jquery-cookie plugin

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

alert(value);
Bhale Dino
  • 248
  • 2
  • 7
  • @cytsunny - this is because you have to have the jquery cookie plugin to use this. – Alex Standiford May 07 '18 at 14:58
  • Wow.... what an important info missing previously.... But from the link you provided, it seems that the owner of the library decided that they better remove the jquery dependency. – cytsunny May 08 '18 at 06:39
3

There are already nice answers here for getting the cookie,However here is my own solution :

function getcookie(cookiename){
var cookiestring  = document.cookie;
var cookiearray = cookiestring.split(';');
for(var i =0 ; i < cookiearray.length ; ++i){ 
    if(cookiearray[i].trim().match('^'+cookiename+'=')){ 
        return cookiearray[i].replace(`${cookiename}=`,'').trim();
    }
} return null;
}

usage :`

     getcookie('session_id');
   // gets cookie with name session_id
Ewomazino Ukah
  • 2,286
  • 4
  • 24
  • 40
3

Just use the following function (a pure javascript code)

const getCookie = (name) => {
 const cookies = Object.assign({}, ...document.cookie.split('; ').map(cookie => {
    const name = cookie.split('=')[0];
    const value = cookie.split('=')[1];

    return {[name]: value};
  }));

  return cookies[name];
};
Amjed Omar
  • 853
  • 2
  • 14
  • 30
3
function getCookie(cname) {
  var name = cname + "=";
  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);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

Pass the cookie name to getCookie() function to get it's value

2

My solution is this:

function getCookieValue(cookieName) {
    var ca = document.cookie.split('; ');
    return _.find(ca, function (cookie) {
        return cookie.indexOf(cookieName) === 0;
    });
}

This function uses the Underscorejs _.find-function. Returns undefined if cookie name doesn't exist

atlefren
  • 210
  • 4
  • 10
2

I have done it this way. so that i get an object to access to separate the values.With this u can pass the cookie to the parent and then you can access your values by the keys like

var cookies=getCookieVal(mycookie);
alert(cookies.mykey);
function getCookieVal(parent) {
            var cookievalue = $.cookie(parent).split('&');
            var obj = {};
            $.each(cookievalue, function (i, v) {
                var key = v.substr(0, v.indexOf("="));
                var val = v.substr(v.indexOf("=") + 1, v.length);

                obj[key] = val;

            });
            return obj;
        }  
saydur rahman
  • 119
  • 1
  • 9
2

I wrote something that might be easy to use, If anyone has some things to add, feel free to do so.

function getcookie(name = '') {
    let cookies = document.cookie;
    let cookiestore = {};
    
    cookies = cookies.split(";");
    
    if (cookies[0] == "" && cookies[0][0] == undefined) {
        return undefined;
    }
    
    cookies.forEach(function(cookie) {
        cookie = cookie.split(/=(.+)/);
        if (cookie[0].substr(0, 1) == ' ') {
            cookie[0] = cookie[0].substr(1);
        }
        cookiestore[cookie[0]] = cookie[1];
    });
    
    return (name !== '' ? cookiestore[name] : cookiestore);
}

Usage

getcookie() - returns an object with all cookies on the web page.

getcookie('myCookie') - returns the value of the cookie myCookie from the cookie object, otherwise returns undefined if the cookie is empty or not set.


Example

// Have some cookies :-)
document.cookie = "myCookies=delicious";
document.cookie = "myComputer=good";
document.cookie = "myBrowser=RAM hungry";

// Read them
console.log( "My cookies are " + getcookie('myCookie') );
// Outputs: My cookies are delicious

console.log( "My computer is " + getcookie('myComputer') );
// Outputs: My computer is good

console.log( "My browser is " + getcookie('myBrowser') );
// Outputs: My browser is RAM hungry

console.log( getcookie() );
// Outputs: {myCookie: "delicious", myComputer: "good", myBrowser: "RAM hungry"}

// (does cookie exist?)
if (getcookie('hidden_cookie')) {
    console.log('Hidden cookie was found!');
} else {
    console.log('Still no cookie :-(');
}

// (do any cookies exist?)
if (getcookie()) {
    console.log("You've got cookies to eat!");
} else {
    console.log('No cookies for today :-(');
}
2

Set-Cookie in JS

document.cookie = 'fb-event-id=15648779++';

Get Cookies by name funcation

function getCookie(name) {
    // Split cookie string and get all individual name=value pairs in an array
    var cookieArr = document.cookie.split(";");
    // Loop through the array elements
    for(var i = 0; i < cookieArr.length; i++) {
        var cookiePair = cookieArr[i].split("=");
        /* Removing whitespace at the beginning of the cookie name
        and compare it with the given string */
        if(name == cookiePair[0].trim()) {
            // Decode the cookie value and return
            return decodeURIComponent(cookiePair[1]);
        }
    } 
    // Return null if not found
    return null;
}

This is how to use the getCookie function

var eventID = getCookie('fb-event-id')
Mohit Sharma
  • 529
  • 1
  • 6
  • 17
1

A functional approach to find existing cookies. It returns an array, so it supports multiple occurrences of the same name. It doesn't support partial key matching, but it's trivial to replace the === in the filter with a regex.

function getCookie(needle) {
    return document.cookie.split(';').map(function(cookiestring) {
        cs = cookiestring.trim().split('=');

        if(cs.length === 2) {
            return {'name' : cs[0], 'value' : cs[1]};
        } else {
            return {'name' : '', 'value' : ''};
        }
    })
    .filter(function(cookieObject) { 
        return (cookieObject.name === needle);
    });
}
79man
  • 31
  • 5
1

Get cookie by name just pass the name of cookie to below function

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
Kalpit tandon
  • 119
  • 1
  • 3
  • 10
1

This method working perfectly out of the box

function getCookie(cname) {
  var cookies = ` ${document.cookie}`.split(";");
  var val = "";
  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i].split("=");
    if (cookie[0] == ` ${cname}`) {
      return cookie[1];
    }
  }
  return "";
}
nhCoder
  • 451
  • 5
  • 11
  • Split into your array with `.split('; ')` (with a space), then don't add a space when checking `cookie[0]`, and it's a little less opaque. – Spirko Jul 17 '22 at 15:58
1
Object.fromEntries(
    document.cookie.split(';').map(item => {
      return item.trim().split('=', 2);
    }),
  );
Bald
  • 2,156
  • 3
  • 24
  • 33
0

Following function will return a key-value pair of the required cookie, where key is the cookie name and value will be the value of the cookie.

/**
 * Returns cookie key-value pair
 */
var getCookieByName = function(name) {
    var result = ['-1','-1'];
    if(name) {
        var cookieList = document.cookie.split(';');
        result = $.grep(cookieList,function(cookie) { 
            cookie = cookie.split('=')[0];
            return cookie == name;
        });
    }
    return result;
};
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
0

Cookies example: example JS:

document.cookies = {
   create : function(key, value, time){
     if (time) {
         var date = new Date();
         date.setTime(date.getTime()+(time*24*60*60*1000));
         var expires = "; expires="+date.toGMTString();
     }
     else var expires = "";
     document.cookie = key+"="+value+expires+"; path=/";
   },
   erase : function(key){
     this.create(key,"",-1);
   },
   read : function(key){
     var keyX = key + "=";
     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(keyX) == 0) return   c.substring(keyX.length,c.length);
     }
     return null;
   }
}

Store arrays and objects with json or xml

Kelk
  • 63
  • 1
  • 7
0

I would do something like this:

function getCookie(cookie){
  return cookie
    .trim()
    .split(';')
    .map(function(line){return line.split(',');})
    .reduce(function(props,line) {
      var name = line[0].slice(0,line[0].search('='));
      var value = line[0].slice(line[0].search('='));
      props[name] = value;
      return props;
    },{})
}

This will return your cookie as an object.

And then you can call it like this:

getCookie(document.cookie)['shares']
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Julian Tellez
  • 802
  • 7
  • 6
0

I like to use a closure for getting cookie values by name. The closure below will allow you to get a cookie value by name but will only parse the cookie string if it has been updated.

You can retrieve the value of a cookie with the following:

var foo = cookies.get( "bar" );

Code:

var cookies = ( function() {
    var cookieString = null;
    var cookieArray = [];

    function getValOf( name ) {
        if ( newCookies() ) {
            parseCookieString()
        }
        return cookieArray[ name ];
    }

    // Check if new cookies have been added
    function newCookies() {
        return cookieString === document.cookie;
    }

    function parseCookieString() {
        cookieString = document.cookie;

        // Separate cookies
        var cookies = cookieString.split( ";" );

        // Empty previous cookies
        cookieArray = [];

        // Update cookieArray with new name-value pairs
        for ( var i in cookies ) {

            // Separate name and value
            var nameVal = cookies[ i ].split( "=" );
            var name = nameVal[ 0 ].trim();
            var value = nameVal[ 1 ].trim();

            // Add cookie name value pair to dictionary
            cookieArray[ name ] = value;
        }
    }

    return {

        /**
         * Returns value or undefined
         */
        get: function( name ) {
            return getValOf( name );
        }  
    };
})();
0

Just to add an "official" answer to this response, I'm copy/pasting the solution to set and retrieve cookies from MDN (here's the JSfiddle

    document.cookie = "test1=Hello";
    document.cookie = "test2=World";

    var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");

    function alertCookieValue() {
      alert(cookieValue);
    }

In you particular case, you would use the following function

    function getCookieValue() {
      return document.cookie.replace(/(?:(?:^|.*;\s*)obligations\s*\=\s*([^;]*).*$)|^.*$/, "$1");
    }

Note that i only replaced "test2" from the example, with "obligations".

Erenor Paz
  • 3,061
  • 4
  • 37
  • 44
0

reference: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

document.cookie = "test1=Hello";
document.cookie = "test2=World";

var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");

  alert(cookieValue);
vidur punj
  • 5,019
  • 4
  • 46
  • 65
0

now you can get cookies to return as an array when you stored cookies in an array format. for example your cookie is array[35]=Khóa; array[36]=Tử; array[37]=Cửa; and this code with utf8 too. one thing doesn't work well when your cookie name content [] in it and you store the cookies is not in the array.

function getCookie(cname) {

            var ca = decodeURIComponent(document.cookie).split(';');


            if (cname.indexOf('[]') > 0) {
                var returnVAlue = [];
                var nameArray = cname.replace("[]", "");

                for(var i = 0; i < ca.length; i++) {
                    var c = ca[i];
                   // console.log(c);
                    while (c.charAt(0) == ' ') {
                        c = c.substring(1);
                    }

                    if (c.indexOf(nameArray) >= 0) {
                        var valueString = c.substr(nameArray.length, c.length);

                        var valueStringSlit = valueString.split('=');
                        valueStringSlit[0] = valueStringSlit[0].substr(1,(valueStringSlit[0].length - 2));
                    //    console.log(valueStringSlit);

                        returnVAlue.push(valueStringSlit);
                    }
                }
            } else {
                var returnVAlue = '';
                var name = cname + "=";

                for(var i = 0; i < ca.length; i++) {
                    var c = ca[i];
                   // console.log(c);
                    while (c.charAt(0) == ' ') {
                        c = c.substring(1);
                    }
                    if (c.indexOf(name) == 0) {
                        returnVAlue = c.substr(name.length, c.length);
                    } 
                }
            }


            if (returnVAlue != ''){
                return returnVAlue;
            } 
            return "";
        }

       // console.log(decodeURIComponent(document.cookie));


        console.log(getCookie('array[]'));
Võ Minh
  • 155
  • 2
  • 12
  • 1
    nonsense for a vote down. while it works perfectly when you save the cookie in the array format. I did a search and no one give the answer for reading cookie array format before this one. – Võ Minh Oct 18 '18 at 22:22
0
Document.cookie The Document property cookie lets you read and write cookies associated with the document. It serves as a getter and setter for the actual values of the cookies.
var c = 'Yash' + '=' + 'Yash-777';
document.cookie = c; // Set the value: "Yash=Yash-777"
document.cookie      // Get the value:"Yash=Yash-777"

From Google GWT project Cookies.java class native code. I have prepared the following functions to perform actions on Cookie.

Function to get all the cookies list as JSON object.

var uriEncoding = false;
function loadCookiesList() {
    var json = new Object();
    if (typeof document === 'undefined') {
        return json;
    }

    var docCookie = document.cookie;
    if (docCookie && docCookie != '') {
      var crumbs = docCookie.split('; ');
      for (var i = crumbs.length - 1; i >= 0; --i) {
        var name, value;
        var eqIdx = crumbs[i].indexOf('=');
        if (eqIdx == -1) {
          name = crumbs[i];
          value = '';
        } else {
          name = crumbs[i].substring(0, eqIdx);
          value = crumbs[i].substring(eqIdx + 1);
        }
        if (uriEncoding) {
          try {
            name = decodeURIComponent(name);
          } catch (e) {
            // ignore error, keep undecoded name
          }
          try {
            value = decodeURIComponent(value);
          } catch (e) {
            // ignore error, keep undecoded value
          }
        }
        json[name] = value;
      }
    }
    return json;
 }

To set and Get a Cookie with a particular Name.

function getCookieValue(name) {
    var json = loadCookiesList();
    return json[name];
}

function setCookie(name, value, expires, domain, path, isSecure) {
    var c = name + '=' + value;
    if ( expires != null) {
        if (typeof expires === 'number') {
            // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
            var timeInMs = Date.now();
            if (expires > timeInMs ) {
                console.log("Seting Cookie with provided expire time.");
                c += ';expires=' + (new Date(expires)).toGMTString();
            } else if (expires < timeInMs) {
                console.log("Seting Cookie with Old expire time, which is in Expired State.");
                timeInMs = new Date(timeInMs + 1000 * expires);
                c += ';expires=' + (new Date(timeInMs)).toGMTString();
            }
        } else if (expires instanceof window.Date) {
            c += ';expires=' + expires.toGMTString();
        }
    }

    if (domain != null && typeof domain == 'string')
      c += ';domain=' + domain;
    if (path != null && typeof path == 'string')
      c += ';path=' + path;
    if (isSecure != null && typeof path == 'boolean')
      c += ';secure';

    if (uriEncoding) {
        encodeURIComponent(String(name))
            .replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent)
            .replace(/[\(\)]/g, escape);
        encodeURIComponent(String(value))
            .replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);

    }
    document.cookie = c;
}

function removeCookie(name) {
    document.cookie = name + "=;expires=Fri, 02-Jan-1970 00:00:00 GMT"; 
}
function removeCookie(name, path) {
    document.cookie = name + "=;path=" + path + ";expires=Fri, 02-Jan-1970 00:00:00 GMT";
}

Checks whether a cookie name is valid: can't contain '=', ';', ',', or whitespace. Can't begin with $.

function isValidCookieName(name) {
    if (uriEncoding) {
      // check not necessary
      return true;
    } else if (name.includes("=") || name.includes(";") || name.includes(",") || name.startsWith("$") || spacesCheck(name) ) {
      return false;
    } else {
      return true;
    }
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
function spacesCheck(name) {
    var whitespace = new RegExp('.*\\s+.*');
    var result = whitespace.test(name);
    console.log("Name:isContainSpace = ", name, ":", result);
    return result;
}

Test steps to check the above functions:

setCookie("yash1", "Yash-777");
setCookie("yash2", "Yash-Date.now()", Date.now() + 1000 * 30);
setCookie("yash3", "Yash-Sec-Feature", 30);
setCookie("yash4", "Yash-Date", new Date('November 30, 2020 23:15:30'));

getCookieValue("yash4"); // Yash-Date
getCookieValue("unknownkey"); // undefined

var t1 = "Yash", t2 = "Y    ash", t3 = "Yash\n";
spacesCheck(t1); // False
spacesCheck(t2); // True
spacesCheck(t3); // True
Yash
  • 9,250
  • 2
  • 69
  • 74
0
const cookies = 'key1=chocolate; key2=iceCream; key3=cookies;';

// convert string into array with split
const arrCookies = cookies.split('; '); // [ 'key1=chocolate', 'key2=iceCream', 'key3=cookies' ]

// split key value by equal sign
const arrArrCookiesKeyValue = arrCookies.map(cookie => [cookie.split('=')]);  // [[['key1', 'chocolate']], ...']

// make an object with key value
const objectKeyValueCookies = {}; // { key1: 'chocolate', key2: 'iceCream', key3: 'cookies;' }
for (let arr of arrArrCookiesKeyValue) {
    objectKeyValueCookies[arr[0][0]] = arr[0][1];
}

// find the key in object
const findValueByKey = (key = null, objectCookies) => objectCookies[key];
console.log(findValueByKey('key2', objectKeyValueCookies)); // chocolate
Hector
  • 636
  • 8
  • 16
0

This works perfect for me (assuming that the cookie name is unique):

function getCookie(name) {
    var cookies = document.cookie;
    var parts = cookies.split(name + "=");
    var cookieValue = '';
    if (parts.length == 2) {
        cookieValue = parts.pop().split(";").shift();
    }
    return cookieValue;
}
Shessuky
  • 1,846
  • 21
  • 24
0

I had an issue where sometimes two cookies with the same name would be saved to the browser. I couldn't figure out how to stop this from happening. But I learned how you can get the most recent cookie that was saved instead of the first cookie saved.

Here's the code:

    const getCookie = (name) => {
        const match = document.cookie.split(';').map(el => { let [key,value] = el.split('='); return { [key.trim()]: value }})
        const filteredMatch = match.filter(e => Object.keys(e)[0] === name)

        let matchLength = filteredMatch.length

        return filteredMatch[matchLength - 1][name]
    }
Page COW
  • 515
  • 13
  • 31
-1

I wrote this to work with Internet Explorer 11 and modern browsers like Chromium Edge and Firefox.

This gets a cookie value where the HttpOnly attribute is false.

    function getCookieValue(keyName) {

        let returnValue = undefined;

        if (keyName && document.cookie) {

            let cookieArray = decodeURIComponent(document.cookie).split('; ');
            for (var i = 0; i < cookieArray.length; i++) {

                if (cookieArray[i]) {
                    let key = cookieArray[i].split('=')[0];
                    if (key && key === keyName) {
                        let value = cookieArray[i].split('=')[1];
                        returnValue = value;
                        break;
                    }
                }

            }

        }

        return returnValue;

    }
nimblebit
  • 473
  • 3
  • 11
  • 22
-1

You could make use of array methods to filter data and save coding lines:

const extractFrom = (name) => {
        let data = document.cookie.split(' ').find(e => e.startsWith(name));
        if(data) {
            return data.substring((data.indexOf('=') + 1), (data.length -1));
        } else {
            return null;
        }
    }
-1

Pure functional way


// convert cookies to object

const cookies = Object.assign(
    {}, 
    ...document.cookie.split(';')
        .filter(s => s)
        .map(cookie => cookie.split('='))
        .map(([key, value]) => ({ 
            [key.trim()]: (value+'').trim() 
        }))
);

// usage

console.log(cookies.shared);
console.log(cookies.obligations);

One liner

const cookies = Object.assign({}, ...document.cookie.split(';').filter(s => s).map(cookie => cookie.split('=')).map(([key, value]) => ({ [key.trim()]: (value+'').trim() })));

// usage

console.log(cookies.shared);
console.log(cookies.obligations);

As function with name argument

const getCookie = name => Object.assign({}, ...document.cookie.split(';').filter(s => s).map(cookie => cookie.split('=')).map(([key, value]) => ({ [key.trim()]: (value+'').trim() })))[name];

// usage

console.log(getCookie('shred'));
console.log(getCookie('obligations'));

One liner for single value

const shared = Object.assign({}, ...document.cookie.split(';').filter(s => s).map(cookie => cookie.split('=')).map(([key, value]) => ({ [key.trim()]: (value+'').trim() }))).shared;

// usage

console.log(shared);

UPD: fixed trim() error for empty cookie values

UPD2: fixed "" key for empty cookies

-2
function GetCookieValue(name) {
    var found = document.cookie.split(';').filter(c => c.trim().split("=")[0] === name);
    return found.length > 0 ? found[0].split("=")[1] : null;
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
Coreman
  • 1
  • 1