Skip to main content Accessibility Feedback

getCookie.js

Get the value of a cookie.

Source Code

Example

// Set a cookie named sandwich, with a value of turkey
// Cookie expires on December 31, 2024 at 11:59 and 59 seconds PM
document.cookie = 'sandwich=turkey;';

// returns "turkey"
let sandwich = getCookie('sandwich');

The helper function

/**
 * Get the value of a cookie
 * Source: https://gist.github.com/wpsmith/6cf23551dd140fb72ae7
 * @param  {String} name  The name of the cookie
 * @return {String}       The cookie value
 */
function getCookie (name) {
	let value = '; ' + document.cookie;
	let parts = value.split(`; ${name}=`);
	if (parts.length == 2) return parts.pop().split(';').shift();
}

Find this useful? You can support my work by purchasing an annual membership.