Setting Multiple Value in Single Cookie

Course- Javascript >

Each cookie contains one name=value pair, so if you need to store several separate pieces of data such as a user’s name, age, and membership number, you need three different cookies.

However, with a little ingenuity you can make your cookie store all three values by concatenating the required values into a single string, which becomes the value stored by your cookie.

This way, instead of having three separate cookies for name, age, and membership number, you could have just one, perhaps named user, containing all three pieces of data. To separate the details later, you place in your value string a special character called a delimiter to separate the different pieces of data:

var userdata = "Sandy|26|A23679";
createCookie("user", userdata);

Here the | (pipe) character acts as the delimiter. When you later retrieve the cookie value, you can split it into its separate variable values by using the | delimiter:

var myUser = getCookie("user");
var myUserArray = myUser.split('|');
var name = myUserArray[0];
var age = myUserArray[1];
var memNo = myUserArray[2];                    
                    

Cookies that store multiple values use up fewer of the 20 cookies per domain allowed by some browsers, but remember that your use of cookies is still subject to the 4KB overall limit for cookie information

This is a further example of serialization, which you learned about in section, “Javascript with JSON.”