w3resource

JavaScript: Serialize a cookie name-value pair into a Set-Cookie header string

JavaScript fundamental (ES6 Syntax): Exercise-147 with Solution

Serialize Cookie Name-Value to Set-Cookie Header

Write a JavaScript program to serialize a cookie name-value pair into a Set-Cookie header string.

  • Use template literals and encodeURIComponent() to create the appropriate string.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2

// Define the serializeCookie function
const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`;

// Serialize a cookie with name 'foo' and value 'bar'
console.log(serializeCookie('foo', 'bar')); // Output: "foo=bar"

Output:

foo=bar

Visual Presentation:

JavaScript Fundamental: Serialize a cookie name-value pair into a Set-Cookie header string.

Flowchart:

flowchart: Serialize a cookie name-value pair into a Set-Cookie header string

Live Demo:

See the Pen javascript-basic-exercise-147-1 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that serializes a cookie name-value pair into a valid Set-Cookie header string.
  • Write a JavaScript function that formats a cookie string with attributes such as path, domain, and expiration.
  • Write a JavaScript program that constructs a Set-Cookie header from given cookie parameters and validates the format.

Go to:


PREV : Shallow Clone Object.
NEXT : Hash String to Whole Number.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.