简体   繁体   中英

Get a cookie's single value javascript

I already have a script that check for the cookies existence, but i need it to get the cookies value so i can use it in a url like this:

var lang = cookievalue;
location.replace(window.location.protocol+"//"+document.domain+"/"+cookievalue+window.location.pathname);

so what would be the easiest way to simply get the value of a cookie through javascript, everything i've looked for seems to involve spliting the value and stuff,w hich is not necesary since theres simply only one value (en,fr,es etc)

function getCookieValue(key) {
  var cookies = document.cookie.split('; ');
  for (var i = 0, parts; (parts = cookies[i] && cookies[i].split('=')); i++) {
    if (decode(parts.shift()) === key) {
      return decode(parts.join('='));
    }
  }
  return null;
}

function decode(s) {
  return decodeURIComponent(s.replace(/\+/g, ' '));
}

Then, to get a value for a cookie named my_cookie_name , you would use getCookieValue('my_cookie_name') .

Also as an alternative , you can use the jquery-cookie plugin. It's very simple to use ( $.cookie('my_cookie_name') ) and lightweight.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM