JavaScript Code

How to iterate over cookies?


Tutorials using JS

Problem Statement

iterate over cookies for the document/web-page

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

<!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