Skip to content

Instantly share code, notes, and snippets.

@alekssamos
Created June 25, 2019 02:30
Show Gist options
  • Save alekssamos/82980f1eb9c185208b2edef8ab8adf66 to your computer and use it in GitHub Desktop.
Save alekssamos/82980f1eb9c185208b2edef8ab8adf66 to your computer and use it in GitHub Desktop.
convenient functions for working with cookies in js. I found on the site javascript ru, I have been using for more than 5 years. I like.
function getCookie(name) {
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
))
return matches ? decodeURIComponent(matches[1]) : undefined
}
function setCookie(name, value, props) {
props = props || {}
var exp = props.expires
if (typeof exp == "number" && exp) {
var d = new Date()
d.setTime(d.getTime() + exp*1000)
exp = props.expires = d
}
if(exp && exp.toUTCString) { props.expires = exp.toUTCString() }
value = encodeURIComponent(value)
var updatedCookie = name + "=" + value
for(var propName in props){
updatedCookie += "; " + propName
var propValue = props[propName]
if(propValue !== true){ updatedCookie += "=" + propValue }
}
document.cookie = updatedCookie
}
function deleteCookie(name) {
setCookie(name, null, { expires: -1 })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment