JavaScript Code

How to iterate over cookies?

Tutorials using JS

Problem Statement

iterate over cookies for the document/web-page


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


<!DOCTYPE html>
<div id="output"></div>

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>';


Copyright @2022