Created
April 9, 2014 16:36
-
-
Save fentas/10289901 to your computer and use it in GitHub Desktop.
Simple js for converting cookie string into object
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.
thank you brother
…On Sun, 24 Oct 2021 at 11:02, Jan Guth ***@***.***> wrote:
***@***.**** commented on this gist.
------------------------------
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 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.
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<https://gist.github.com/10289901#gistcomment-3937652>, or unsubscribe
<https://github.com/notifications/unsubscribe-auth/ASDESVHMK5PLJTIHL3ARFLTUIO4SPANCNFSM5GRIQRTQ>
.
Triage notifications on the go with GitHub Mobile for iOS
<https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675>
or Android
<https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub>.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
is there an explanation for the code it works thank you a lot but I just wanna know how it worked <3