2

I search Google but found entire functions to get cookie value. Isn't there one line statement to retrieve cookie value in javascript?

1
  • 1
    This is an oversight in javascript. Yes, you could use another library to do this for you, but they are in essence implementing the functions you keep seeing. If you're already using another library, go ahead. If you are not, you have to weigh downloading an relatively large library (jquery: 31KB, Minified and Gzipped) vs adding less than 1K of js. Commented Jun 22, 2011 at 15:38

3 Answers 3

2

try document.cookie. Here is a good link

Sign up to request clarification or add additional context in comments.

2 Comments

That is the link I meant. I don't want to include those functions.
understood.Any specific reasons?
1

You could use a javascript library, e.g. jQuery in addition with a plugin: http://plugins.jquery.com/project/cookie

Demo page: http://stilbuero.de/jquery/cookie/

Comments

0

You can use the following one liner to convert your cookie to a map and then access whatever parameter you need.

let cookieMap = document.cookie.split(";").map((str)=>str.split("=")).reduce(function(map,curr){map[curr[0]]=curr[1];return map},{})

You can checkout https://stackoverflow.com/a/59994987/7810354 for an explanation of how this works.

1 Comment

Some cookies (at least in my browser) are split with "; " (note the space). So a better split pattern would be document.cookie.split(/;\s*/).map...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.