Skip to content

Instantly share code, notes, and snippets.

@morficus
Last active August 29, 2015 14:22
Show Gist options
  • Select an option

  • Save morficus/041c8e9f63eb0cde36ef to your computer and use it in GitHub Desktop.

Select an option

Save morficus/041c8e9f63eb0cde36ef to your computer and use it in GitHub Desktop.
Constant-time helper function to get a particular value from a cookie with in the broswer
function getCookieValue(key) {
var namePosition,
nameValuePair,
value;
//step 0: append an equal sign to the key we are looking for
key = key + '=';
//step #1: find the position of the particular key we want with in the cookie string of the
namePosition = document.cookie.indexOf(key);
//no value with that name in the cookie
if (namePosition === -1) {
return '';
}
//step #2: now that we know where they key is located, we can eliminate the parts of the cookie string we are sure we do not care about.
//(aka: everything BEFORE the key)
//This will put the the key we are looking for at the very beginning of the string
nameValuePair = document.cookie.substring(namePosition);
//step #3: split the remaining cookie string in to an array of key-value strings.
//Because of step #2, we are certain that the first element in the string is is key-value string we want
nameValuePair = nameValuePair.split(';')[0];
//step#4 (final step): extract the value from the key-value string
value = nameValuePair.split('=')[1];
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment