Get cookie by name

前端 未结 30 1775
野的像风
野的像风 2020-11-22 03:58

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

30条回答
  •  不要未来只要你来
    2020-11-22 04:31

    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.

提交回复
热议问题