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
Here is a one liner to get a cookie with a specific name without the need of any external lib:
var cookie = ("; "+document.cookie).split("; YOUR_COOKIE_NAME=").pop().split(";").shift();
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.
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'
If you just need to check if some cookie exist then simple do this:
document.cookie.split('logged=true').length == 2
if cookie logged=true exist, you will get 2, if not 1.
logged=true - change this to you cookie name=value, or just a name
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.
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
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.