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]);
}
}
It seems to me you could split the cookie key-value pairs into an array and base your search on that:
Which runs the following:
Fiddle: http://jsfiddle.net/qFmPc/
Or possibly even the following:
Apparently MDN has never heard of the word-boundary regex character class
\b
, which matches contiguous\w+
that is bounded on either side with\W+
:Cookies example: example JS:
Store arrays and objects with json or xml
use a cookie getting script:
then call it:
i stole the code above from quirksmode cookies page. you should read it.
The methods in some of the other answers that use a regular expression do not cover all cases, particularly:
The following method handles these cases:
This will return
null
if the cookie is not found. It will return an empty string if the value of the cookie is empty.Notes:
document.cookie
- When this appears on the right-hand side of an assignment, it represents a string containing a semicolon-separated list of cookies, which in turn arename=value
pairs. There appears to be a single space after each semicolon.String.prototype.match()
- Returnsnull
when no match is found. Returns an array when a match is found, and the element at index[1]
is the value of the first matching group.Regular Expression Notes:
(?:xxxx)
- forms a non-matching group.^
- matches the start of the string.|
- separates alternative patterns for the group.;\\s*
- matches one semi-colon followed by zero or more whitespace characters.=
- matches one equal sign.(xxxx)
- forms a matching group.[^;]*
- matches zero or more characters other than a semi-colon. This means it will match characters up to, but not including, a semi-colon or to the end of the string.Simple function for Get cookie with cookie name: