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]);
}
}
A functional approach to find existing cookies. It returns an array, so it supports multiple occurrences of the same name. It doesn't support partial key matching, but it's trivial to replace the === in the filter with a regex.
kirlich gave a good solution. However, it fails when there are two cookie values with similar names, here is a simple fix for this situation:
You can use js-cookie library to get and set JavaScript cookies.
Include to your HTML:
To create a Cookie:
To read a Cookie:
I like to use a closure for getting cookie values by name. The closure below will allow you to get a cookie value by name but will only parse the cookie string if it has been updated.
You can retrieve the value of a cookie with the following:
Code:
I have modified the function that Jonathan provided here, by using regular expression you can get a cookie value by its name like this:
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.
Following function will return a
key-value
pair of the required cookie, wherekey
is the cookie name andvalue
will be the value of the cookie.