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
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:
function getCookie(name) {
function escape(s) { return s.replace(/([.*+?\^$(){}|\[\]\/\\])/g, '\\$1'); }
var match = document.cookie.match(RegExp('(?:^|;\\s*)' + escape(name) + '=([^;]*)'));
return match ? match[1] : null;
}
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:
name=value pairs. There appears to be a single space after each semicolon.null 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.