I search Google but found entire functions to get cookie value. Isn't there one line statement to retrieve cookie value in javascript?
-
1This 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.evan– evan2011-06-22 15:38:00 +00:00Commented Jun 22, 2011 at 15:38
Add a comment
|
3 Answers
try document.cookie. Here is a good link
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
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
Nathan Wallace
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...