How to simply set and read cookies with Javascript ?

Could you please give an example of simple short code for setting and reading cookies ?
0
give a positive ratinggive a negative rating
Hi,

You can simply set session cookie, where name is "abc" and value is "123", with this code:

document.cookie = 'abc=123; path=/';

To set a persistent cookie with calculated expiry time, you can use this code:

var d = new Date();
d.setTime(d.getTime()+(3600*1000));
var e = '; expires=' + d.toUTCString();
document.cookie = 'abc=123'+e+'; path=/';


You can also set cookie by this code, if you know the exact expiry date:

document.cookie = 'abc=123; expires=Thu, 12 Aug 2019 15:30:00 UTC; path=/';

To read value of cookie "abc", you can use this code:

var c = document.cookie.match(new RegExp('(^| )abc=([^;]+)'));
if (c){ alert(c[2]); }


Share on FacebookShare on TwitterShare on LinkedInSend email
1 answer
x
x
2024 AnswerTabsTermsContact us