Created
September 12, 2017 06:50
-
-
Save joduplessis/7b3b4340353760e945f972a69e855d11 to your computer and use it in GitHub Desktop.
Setting, deleting and retrieving cookies in Typescript.
Just commenting to say that with the latest typescript you could solve the pop undefined scenario like this
export function getCookie(name: string) {
const value = "; " + document.cookie;
const parts = value.split("; " + name + "=");
if (parts.length == 2) {
return parts.pop()?.split(";").shift();
}
}
Alternatively if you'd like to consistently return a string you could do it like this
return (
(parts.length === 2 &&
parts
.pop()
?.split(";")
.shift()) ||
""
);
thank you krub
Thank you. This has helped me weening myself from jQuery Libraries...and morphing my js to ts.
For those seeing this thread in 2023, getting a cookie can be implemented as
const getCookie = (cookieName: string) => new RegExp(`${cookieName}=([^;]+);`).exec(document.cookie)?.[1];
which IMHO is more elegant than shifting values out of an array and splitting out all cookie entries first.
@mctrafik this is good but readability could be better.
Better to use parts.length === 2
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You are missing the return type for
getCookie
.