Get cookie by name

2018-12-31 10:14发布

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]);
    }
 }

30条回答
栀子花@的思念
2楼-- · 2018-12-31 11:11

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']
查看更多
爱死公子算了
3楼-- · 2018-12-31 11:12

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
查看更多
查无此人
4楼-- · 2018-12-31 11:13

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];
}

Improved thanks to Scott Jungwirth in the comments.

查看更多
无色无味的生活
5楼-- · 2018-12-31 11:13
function getCookie(name) {
    var pair = document.cookie.split('; ').find(x => x.startsWith(name+'='));
    if (pair)
       return pair.split('=')[1]
}
查看更多
孤独寂梦人
6楼-- · 2018-12-31 11:16

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.

查看更多
柔情千种
7楼-- · 2018-12-31 11:16

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);
}
查看更多
登录 后发表回答