Apparently to retrieve cookies we have loops, splits, multiple RegExp, and any other sort of alchemy ... but are these functions the only one we need to read cookies?
var Cookie = {
get:function (name) {
var match = document.cookie.match(
new RegExp("(?:^|;\\s*)" + name + "=([^;]*?)", "g")
);
return match && match[1];
},
getAll:function () {
var re = new RegExp("([^=]+?)=([^;]*?)(?:;\\s*|$)", "g"),
cookie = "" + document.cookie,
result = {},
match
;
while(match = re.exec(cookie))
result[match[1]] = match[2]
;
return result;
}
};
I think sometimes we overload methods without a valid reason, but maybe I am missing something ... the only option I could eventually spot is the encode/decode, but as far as I know that is a browser problem, is it?
If we need that, well ...
var Cookie = {
get:function (name, encoded) {
var match = document.cookie.match(
new RegExp("(?:^|;\\s*)" + (encoded ? encodeURIComponent(name) : name) + "=([^;]*?)", "g")
);
return match && decodeURIComponent(match[1]);
},
getAll:function (encoded) {
var re = new RegExp("([^=]+?)=([^;]*?)(?:;\\s*|$)", "g"),
cookie = "" + document.cookie,
result = {},
match
;
while(match = re.exec(cookie))
result[encoded ? decodeURIComponent(match[1]) : match[1]] =
encoded ? decodeURIComponent(match[2]) : match[2];
;
return result;
}
};
No comments:
Post a Comment