Skip to content

Instantly share code, notes, and snippets.

@jacobovidal
Last active July 12, 2017 18:30
Show Gist options
  • Save jacobovidal/72da266c0aeca9b5ed6c7f7836571095 to your computer and use it in GitHub Desktop.
Save jacobovidal/72da266c0aeca9b5ed6c7f7836571095 to your computer and use it in GitHub Desktop.
Set and get cookies function in JavaScript
/**
* @param {string} cname - Cookie name
* @param {string} cvalue - Cookie value
* @param {int} exdays - Cookie expiration time in days
*/
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var path = "path=/",
expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + path + ";" + expires;
}
/**
* @param string [cname] - Cookie name
*/
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment