JavaScript Cookie with Multiple Name
Syntax
To set a cookie with multiple names in JavaScript, use the following syntax:
document.cookie = "name1=value1;name2=value2;expires=date;path=path;domain=domain;secure"
Example
document.cookie = "username=John;language=English;expires=Fri, 31 Dec 2022 23:59:59 GMT;path=/;domain=example.com;secure"
Output
The output of the example will be a cookie with two names:
username
with the value ofJohn
language
with the value ofEnglish
Explanation
In JavaScript, a cookie with multiple names can be set by separating each name-value pair with a semicolon ;
. The expires
option specifies the expiration date of the cookie. The path
option specifies the URL path for which the cookie is valid. The domain
option specifies the domain for which the cookie is valid. The secure
option indicates that the cookie can only be transferred over a secure HTTPS connection.
Use
A cookie with multiple names can be used to store multiple values for a user, such as user preferences or settings. These values can be accessed using JavaScript in subsequent sessions.
Important Points
- Each name-value pair in a cookie with multiple names should be separated by a semicolon
;
- The
expires
option specifies the expiration date, after which the cookie will be deleted. - The
path
option specifies the URL path for which the cookie is valid. - The
domain
option specifies the domain for which the cookie is valid. - The
secure
option indicates that the cookie can only be transferred over a secure HTTPS connection.
Summary
A cookie with multiple names can be set in JavaScript by separating each name-value pair with a semicolon ;
. This cookie can be used to store multiple values for a user and can be accessed using JavaScript in subsequent sessions. Important options for a cookie with multiple names include expires
, path
, domain
, and secure
.