Atom Vayalinkal
Atom Vayalinkal

Reputation: 2692

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)

Upvotes: 1

Views: 6319

Answers (1)

João Silva
João Silva

Reputation: 91299

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.

Upvotes: 6

Related Questions