Skip to content

Instantly share code, notes, and snippets.

@phloe
Last active December 10, 2015 18:49
Show Gist options
  • Save phloe/4477367 to your computer and use it in GitHub Desktop.
Save phloe/4477367 to your computer and use it in GitHub Desktop.
var bake_cookie = (function () {
function decode (string) {
return decodeURIComponent(
string.replace(/%2[1789A]/gi, function(d){
return String.fromCharCode(parseInt(d.slice(1), 16));
})
);
}
function encode (string) {
return encodeURIComponent(string).replace(/[!'()*]/g, function(d){
return "%" + d.charCodeAt(0).toString(16);
});
}
return {
set: function(name, value, exdays){
var exdate,
c_value = encode(value);
if (exdays) {
exdate = new Date();
exdate.setDate(exdate.getDate() + exdays)
c_value += ";expires=" + exdate.toUTCString();
}
document.cookie = encode(name) + "=" + c_value;
},
get: function (name) {
var match = document.cookie.match(new RegExp("(?:^|[ ;]+)" + encode(name) + "=([^;]*)(?:[ ;]+|$)"));
if (match) {
return decode(match[1]);
}
return null;
}
};
}());
// set cookie
bake_cookie.set('test','set',1);
// get cookie
alert(bake_cookie.get('test'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment