Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Read a Cookie with JavaScript

In JavaScript, cookies can be read as follows:

let x = document.cookie;

The document.cookie property returns all cookies as a single string, formatted like this: cookie1=value; cookie2=value; cookie3=value;

Change a Cookie with JavaScript

In JavaScript, you can modify a cookie in the same way you create it.

document.cookie = “username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/”;

Delete a Cookie with JavaScript

Deleting a cookie is straightforward.

You don’t need to specify a value for the cookie; simply set the expires parameter to a past date.

document.cookie = “username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;”;

You should specify the cookie path to ensure you’re deleting the correct cookie.

Some browsers may prevent cookie deletion if the path is not specified.