Skip to content

Instantly share code, notes, and snippets.

@fentas
Created April 9, 2014 16:36
Show Gist options
  • Save fentas/10289901 to your computer and use it in GitHub Desktop.
Save fentas/10289901 to your computer and use it in GitHub Desktop.
Simple js for converting cookie string into object
cookies = {};
// read out cookies
document.cookie.replace(/([^=;]+)=([^;]*)/gi, function(m,key,value) {cookies[key.replace(/(^\s+|\s+$)/g,'')] = value.replace(/(^\s+|\s+$)/g,'');});
@abdulazeez761
Copy link

is there an explanation for the code it works thank you a lot but I just wanna know how it worked <3

@fentas
Copy link
Author

fentas commented Oct 24, 2021

Sure. document.cookie is basically just a string every cookie is a key value pair separated by an ;. So the pattern is <key: name of the cookie>=<value: well, the value of the cookie>[; ... next, and so on].

What this snippet does is break up the key and value part with regex.
([^=;]+)= (key) -> find everything without an = and a ; until an = comes
([^;]*) (value) -> find everything without a ; but * it is optional (empty values)

All matches ( within the (...) ) are passed to a function.
This function fills up the previously declared cookies variable as an assoc array.

replace(/(^\s+|\s+$)/g,'') is just to remove whitespace in front and back. You could replace it with an trim() nowadays.

That's it.

@abdulazeez761
Copy link

abdulazeez761 commented Oct 26, 2021 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment