Cookies are simply small text files that a web server sends to the user’s browser. They contain the following data.
- Name-value pair with actual data.
- The expiry date for when the cookie becomes invalid.
- Domain and path of the server it should be sent to.
Approach: To retrieve all the stored cookies in JavaScript, we can use the document.cookie property but this property returns a single string in which the key-value pair is separated by a “;”. It would be great if we can store the key-value pair into an object as it would make the retrieval process much easier. JavaScript does not provide any methods for such a scenario. So let’s work around this problem.
We need to create a function that will parse the cookie string and would return an object containing all the cookies. This would be a simple process with the following steps.
- Get each individual key-value pair from the cookie string using string.split(“;”).
- Separate keys from values in each pair using string.split(“=”).
- Create an object with all key-value pairs and return the object.
Example: Refer to the comments in the following code for better understanding.
Javascript
<script> function cookieParser(cookieString) { // Return an empty object if cookieString // is empty if (cookieString === "" ) return {}; // Get each individual key-value pairs // from the cookie string // This returns a new array let pairs = cookieString.split( ";" ); // Separate keys from values in each pair string // Returns a new array which looks like // [[key1,value1], [key2,value2], ...] let splittedPairs = pairs.map(cookie => cookie.split( "=" )); // Create an object with all key-value pairs const cookieObj = splittedPairs.reduce( function (obj, cookie) { // cookie[0] is the key of cookie // cookie[1] is the value of the cookie // decodeURIComponent() decodes the cookie // string, to handle cookies with special // characters, e.g. '$'. // string.trim() trims the blank spaces // auround the key and value. obj[decodeURIComponent(cookie[0].trim())] = decodeURIComponent(cookie[1].trim()); return obj; }, {}) return cookieObj; } let dummyCookieString = "username=John; gfg=GeeksForGeeks; foo=education" ; // Pass document.cookie to retrieve actual cookies let cookieObj = cookieParser(dummyCookieString); console.log(`cookie gfg has value ${cookieObj[ 'gfg' ]}.`); console.log(`cookie foo has value ${cookieObj[ 'foo' ]}.`); </script> |
Output:
cookie gfg has value GeeksForGeeks. cookie foo has value education.