Hello friends , In this post i will provide a code that help you to create, read and delete cookies in javascript. You can easily use this code in any html, visualforce page, lightning component and lightning web component. So let's begin,

Create , read and delete cookies in javascript 

Here i will provide two type of example, first for single value and second for object type.

1. Single value

 var name="DemoCookie", value="Demo Value";
 function createcookie() { 
	var cookie = [name, '=', value, '; domain=.', window.location.host.toString(), '; path=/;'].join('');
	document.cookie = cookie;
 }

 function readcookie() {
	var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
	result && (result = result[1]);                
	return result;
 }

 function deletecookie() {
	document.cookie = [name, '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; domain=.', window.location.host.toString()].join('');
 }

Output:


 2. Object type value

 var name="DemoCookie";
var value=[{Name:"First User",Gender:"Male"},{Name:"Second User",Gender:"Female"}];
function createcookie() {
var cookie = [name, '=', JSON.stringify(value), '; domain=.', window.location.host.toString(), '; path=/;'].join('');
document.cookie = cookie;
}

function readcookie() {
var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
result && (result = JSON.parse(result[1]));
return result;
}

function deletecookie() {
document.cookie = [name, '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; domain=.', window.location.host.toString()].join('');
}

Output:


Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.