JavaScript Code


How to iterate over cookies in JavaScript?


Tutorials using JS

Iterate over cookies in JavaScript

In this tutorial, you shall learn how to iterate over cookies of document/web-page using JavaScript.

Solution

To iterate over the cookies of a document, get all the cookies currently present for the document using document.cookie. cookie property returns a semicolon separated list of name-value pairs as shown in the following.

key1=value1; key2=value2; key3=value3

Using the regular expression /; */ as delimiter, split the above value into an array. each element of this array contains key=value. Now split this string value with = as delimiter, we get key and value separated.

Program

When user clicks on the button, we get the cookies string, split it into individual cookies, and show them in the div#output element.

<!DOCTYPE html>
<html>
<body>
<h1>Cookies</h1>
<div id="output"></div>

<script>
var cookies = document.cookie;
var cookiesArray = cookies.split(/; */);
for (let i = 0; i < cookiesArray.length; i++ ) {
    let thisCookie = cookiesArray[i];
    let splitCookie = thisCookie.split('=');
    let key = splitCookie[0];
    let value = splitCookie[1];
    document.getElementById('output').innerHTML += key + ' - ' + value + '<br>';
}
</script>

</body>
</html>


Copyright @2022