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]);
}
}
I would do something like this:
This will return your cookie as an object.
And then you can call it like this:
There are already nice answers here for getting the cookie,However here is my own solution :
usage :`
I would prefer using a single regular expression match on the cookie:
Improved thanks to Scott Jungwirth in the comments.
4 years later, ES6 way simpler version.
I have also created a gist to use it as a
Cookie
object. e.g.,Cookie.set(name,value)
andCookie.get(name)
This read all cookies instead of scanning through. It's ok for small number of cookies.
In my projects I use following function to access cookies by name