Is it possible to create a cookie using arrays?
I would like to store a[0]=\'peter\'
, a[\'1\']=\'esther\'
, a[\'2\']=\'john\'
i
Added remove to cookiemonster
// remove item
cookiemonster.remove('series', 's6', 30); //returns array with values ['s1', 's2', 's3', 's4', 's5', 's7', 's8']
cookiemonster.remove = function (cookieName, item, expDays) {
var cookievalue = cookiemonster.get(cookieName);
//Find the item
for( var i = 0; i < cookievalue.length; i++) {
if ( cookievalue[i] === item) {
cookievalue.splice(i, 1);
}
}
cm_createCookie(cookieName, cm_arrayAsString(cookievalue), expDays);
};
I agree with other comments - you should not be doing this and you should be using JSON. However, to answer your question you could hack this by storing the array as a comma-delimited string. Lets say you wanted to save a the following Javascript array into a cookie:
var a = ['peter','esther','john'];
You could define a cookie string, then iterate over the array:
// Create a timestamp in the future for the cookie so it is valid
var nowPreserve = new Date();
var oneYear = 365*24*60*60*1000; // one year in milliseconds
var thenPreserve = nowPreserve.getTime() + oneYear;
nowPreserve.setTime(thenPreserve);
var expireTime = nowPreserve.toUTCString();
// Define the cookie id and default string
var cookieId = 'arrayCookie';
var cookieStr = '';
// Loop over the array
for(var i=0;i<a.length;i++) {
cookieStr += a[i]+',';
}
// Remove the last comma from the final string
cookieStr = cookieStr.substr(0,cookieStr.length-1);
// Now add the cookie
document.cookie = cookieId+'='+cookieStr+';expires='+expireTime+';domain='+document.domain;
In this example, you would get the following cookie stored (if your domain is www.example.com):
arrayCookie=peter,ester,john;expires=1365094617464;domain=www.example.com
I've created this easy way to get cookies. It'll give error if execute here, but it's functional
var arrayOfCookies = [];
function parseCookieToArray()
{
var cookies = document.cookie;
var arrayCookies = cookies.split(';');
arrayCookies.map(function(originalValue){
var name = originalValue.split('=')[0];
var value = originalValue.split('=')[1];
arrayOfCookies[name] = value;
});
}
console.log(arrayOfCookies); //in my case get out: [language: 'en_US', country: 'brazil']
parseCookieToArray();
New
My new obj to create
get
cookies
cookie = {
set: function(name, value) {
document.cookie = name+"="+value;
},
get: function(name) {
cookies = document.cookie;
r = cookies.split(';').reduce(function(acc, item){
let c = item.split('='); //'nome=Marcelo' transform in Array[0] = 'nome', Array[1] = 'Marcelo'
c[0] = c[0].replace(' ', ''); //remove white space from key cookie
acc[c[0]] = c[1]; //acc == accumulator, he accomulates all data, on ends, return to r variable
return acc; //here do not return to r variable, here return to accumulator
},[]);
}
};
cookie.set('nome', 'Marcelo');
cookie.get('nome');
For that example you can do it quite easily:
Make Cookies:
///W3Schools Cookie Code:
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
///My Own Code:
for(a=0;a<b.length;a++){
setCookie(b[a],b[a],periodoftime);
}
Retrieve Array:
for(a=0;a<b.length;a++){
b[a] = getCookie(b[a])
}
For any array with other value types besides strings:
Make Cookies:
///Replace MyCode above With:
if(typeof b[a] === 'string'){
setCookie(b[a],b[a],periodoftime);
}else{
setCookie(b[a].toString,b[a],periodoftime);
}
Retrieve Array:
for(a=0;a<b.length;a++){
if(typeof b[a] === 'string'){
b[a] = getCookie(b[a])
}else{
b[a] = getCookie(b[a].toString)
}
}
The only flaw is that identical values cannot be retrieved.
No JQuery needed, comma seperation or JSON.
Cookies can hold only strings. If you want to simulate an array you need to serialize it and deserialize it.
You could do this with a JSON library.
I add the code below Script (see the following code) into a javascript file called CookieMonster.js
.
It's a wrapper around the current snippet from http://www.quirksmode.org/js/cookies.html
It works with arrays and strings, it will automagically escape your array/string's commas ,
and semi-colons ;
(which are not handled in the original snippets).
I have listed the simple usage and some bonus usage I built into it.
Usage:
//set cookie with array, expires in 30 days
var newarray = ['s1', 's2', 's3', 's4', 's5', 's6', 's7'];
cookiemonster.set('series', newarray, 30);
var seriesarray = cookiemonster.get('series'); //returns array with the above numbers
//set cookie with string, expires in 30 days
cookiemonster.set('sample', 'sample, string;.', 30);
var messagestring = cookiemonster.get('sample'); //returns string with 'sample, string;.'
Bonuses:
//It also conveniently contains splice and append (works for string or array (single string add only)).
//append string
cookiemonster.append('sample', ' add this', 30); //sample cookie now reads 'sample, string;. add this'
//append array
cookiemonster.append('series', 's8', 30); //returns array with values ['s1', 's2', 's3', 's4', 's5', 's6', 's7', 's8']
//splice
cookiemonster.splice('series', 1, 2, 30); //returns array with values ['s1', 's4', 's5', 's6', 's7', 's8']
CookieMonster.js :
var cookiemonster = new Object();
cookiemonster.append = function (cookieName, item, expDays) {
item = cm_clean(item);
var cookievalue = cookiemonster.get(cookieName);
if (cookievalue instanceof Array) {
cookievalue[cookievalue.length] = item;
cm_createCookie(cookieName, cm_arrayAsString(cookievalue), expDays);
} else {
cm_createCookie(cookieName, cookievalue + item, expDays);
}
};
cookiemonster.splice = function (cookieName, index, numberToRemove, expDays) {
var cookievalue = cookiemonster.get(cookieName);
if (cookievalue instanceof Array) {
cookievalue.splice(index, numberToRemove);
cm_createCookie(cookieName, cm_arrayAsString(cookievalue), expDays);
}
};
cookiemonster.get = function (cookieName) {
var cstring = cm_readCookie(cookieName);
if (cstring.indexOf('<#&type=ArrayVals>') != -1) {
var carray = cstring.split(',');
for (var i = 0; i < carray.length; i++) {
carray[i] = cm_dirty(carray[i]);
}
if (carray[0] == '<#&type=ArrayVals>') {
carray.splice(0, 1);
}
return carray;
} else {
return cm_dirty(cstring);
}
};
cookiemonster.set = function (cookieName, value, expDays) {
if (value instanceof Array) {
cm_createCookie(cookieName, cm_arrayAsString(value), expDays);
}
else { cm_createCookie(cookieName, cm_clean(value), expDays); }
};
cookiemonster.eraseCookie = function (name) {
cm_createCookie(name, "", -1);
};
function cm_replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
};
function cm_clean(ret) {
ret = cm_replaceAll(ret.toString(), ',', ',');
ret = cm_replaceAll(ret.toString(), ';', ';');
return ret;
};
function cm_dirty(ret) {
ret = cm_replaceAll(ret, ',', ',');
ret = cm_replaceAll(ret, ';', ';');
return ret;
};
function cm_createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
};
function cm_readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
};
function cm_arrayAsString(array) {
var ret = "<#&type=ArrayVals>"; //escapes, tells that string is array
for (var i = 0; i < array.length; i++) {
ret = ret + "," + cm_clean(array[i]);
}
return ret;
};