What is the shortest function of reading a cookie by name in JavaScript?


Here’s the best way to read cookies by name in JavaScript. The following is the function −

function ReadCookie() {
   var allcookies = document.cookie;
   document.write ("All Cookies : " + allcookies );

   // Get all the cookies pairs in an array
   cookiearray = allcookies.split(';');

   // Now take key value pair out of this array
   for(var i = 0; i < cookiearray.length; i++) {
      name = cookiearray[i].split('=')[0];
      value = cookiearray[i].split('=')[1];
      document.write ("Key is : " + name + " and Value is : " + value);
   }
}

Updated on: 16-Jun-2020

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements