JavaScript Cookies Read

You are Here:

JavaScript Cookies Read

The document.cookie property reads all cookies from the web browser.

Read Single Cookie

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var name = "Steve"; var uName = ""; //Cookie write document.cookie = "username="+name+";path=/"; // Cookie read all allcookie=(document.cookie); // Convert string to array cookiearray = allcookie.split(";"); // Run through array cookiearray.forEach(function(element) { if(element.indexOf("username")>-1) uName = element.slice((element.indexOf("username=")+9), element.length); }); // Print the username document.write(uName); </script> </body> </html>

Read Multiple Cookie

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var name = "Steve"; var uName = ""; var age = "25"; var uAge = ""; //Cookie write document.cookie = "username="+name+";path=/"; document.cookie = "userage="+age+";path=/"; // Cookie read all allcookie=(document.cookie); // Convert string to array cookiearray = allcookie.split(";"); // Run through array cookiearray.forEach(function(element){ if(element.indexOf("username")>-1) uName = element.slice((element.indexOf("username=")+9), element.length); if(element.indexOf("userage")>-1) uAge = element.slice((element.indexOf("userage=")+8), element.length); }); // Print the username document.write(uName+" is "+uAge+" years old."); </script> </body> </html>

Read Object Cookie

Tips: To convert a string to an object, use JSON.parse

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var bike ={ company: "honda", model: "CBR 1000RR", color: "Red" }; var uBike = ""; //Cookie write document.cookie = "userbike="+JSON.stringify(bike)+";path=/"; //Cookie read all allcookie=(document.cookie); //Convert string to array cookiearray = allcookie.split(";"); //Run through array cookiearray.forEach(function(element) { if(element.indexOf("userbike")>-1) uBike = element.slice((element.indexOf("userbike=")+9), element.length); }); //Convert string to object uBike = JSON.parse(uBike); // Print the name document.write(uBike.company); </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author