1function setCookie(name,value,days) {
2 var expires = "";
3 if (days) {
4 var date = new Date();
5 date.setTime(date.getTime() + (days*24*60*60*1000));
6 expires = "; expires=" + date.toUTCString();
7 }
8 document.cookie = name + "=" + (value || "") + expires + "; path=/";
9}
10function getCookie(name) {
11 var nameEQ = name + "=";
12 var ca = document.cookie.split(';');
13 for(var i=0;i < ca.length;i++) {
14 var c = ca[i];
15 while (c.charAt(0)==' ') c = c.substring(1,c.length);
16 if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
17 }
18 return null;
19}
20
21setCookie("user_email","bobthegreat@gmail.com",30); //set "user_email" cookie, expires in 30 days
22var userEmail=getCookie("user_email");//"bobthegreat@gmail.com"
1const getCookie = (cookie_name) =>{
2 // Construct a RegExp object as to include the variable name
3 const re = new RegExp(`(?<=${cookie_name}=)[^;]*`);
4 try{
5 return document.cookie.match(re)[0]; // Will raise TypeError if cookie is not found
6 }catch{
7 return "this-cookie-doesn't-exist";
8 }
9}
10
11getCookie('csrftoken') // ADZlxZaPSa6k4oyelVBa5iWTtLJW8P3Jf7nhW90L2ZWc5Zcq2vKLO1RRFbaKco3C
12getCookie('_non_existent') // this-cookie-doesn't-exist
13
1
2function setCookie(cname, cvalue, exdays = 999) {
3 const d = new Date();
4 d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
5 const expires = 'expires=' + d.toUTCString();
6 document.cookie = cname + '=' + cvalue + ';' + expires + ';path=/';
7}
8
9function getCookie(cname) {
10 const cookies = Object.fromEntries(
11 document.cookie.split(/; /).map(c => {
12 const [key, v] = c.split('=', 2);
13 return [key, decodeURIComponent(v)];
14 }),
15 );
16 return cookies[cname] || '';
17}
18
19setCookie('language', 'vietnam', 365);
20var userEmail = getCookie('language');
1For storing array inside cookie :
2-----------------------------------
3setter : var json_str = JSON.stringify(arr); cookie.set('mycookie', json_str);
4getter : cookie.get('mycookie'); var arr = JSON.parse(json_str);
5----------------------------------------------------------------------------
6Function common for all type of variable :
7==========================================
8let cookie = {
9 set: function(name, value) {
10 document.cookie = name+"="+value;
11 },
12 get: function(name) {
13 let nameEQ = name + "=";
14 let ca = document.cookie.split(';');
15 for( let i = 0; i < ca.length; i++ ) {
16 let c = ca[i];
17 while (c.charAt(0)==' ') c = c.substring(1,c.length);
18 if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
19 }
20 return null;
21 }
22 }
1function getCookie(cookie, name) {
2 const q = {}
3 cookie?.replace(/\s/g, '')
4 .split(';')
5 .map(i=>i.split('='))
6 .forEach(([key, value]) => {
7 q[key] = value
8 })
9 return q[name]??null;
10}