Reputation: 1
I have a cookie that stores 5 values separated by commas in one cookie. I'm able to retrieve the value of ExampleCookie as follows (as example):
var CookieValue = readCookie('ExampleCookie'); //returns Foo,Bar,Foo1,FooFighter,Bar2
How do I parse through CookieValue to assign individual variables such that I can assign a variable to each of the 5 parts?
I've found ways to do this with PHP but not javascript.
Thanks in advance for any advice.
Upvotes: -1
Views: 7667
Reputation: 1
I quickly realized this was more of a question on Split than about cookies. Here is what i came up w/.
var splits = ExampleCookie.split(",");
var slot1 = splits[0];
var slot2 = splits[1];
var slot3 = splits[2]; etc.
Upvotes: 0
Reputation: 4419
JSON.stringify, and JSON.parse are your best cleanest bets (imho)
var values = JSON.parse(readCookie('ExampleCookie'));
createCookie('ExampleCookie',JSON.stringify(values));
This has the added benefit of being able to set key values in your object/array.
Assuming you're using the functions found at quirks mode just ensure your cookie values stringified don't go over the 4000 char limit found in most browsers.
Upvotes: 0
Reputation: 1176
You could split the CookieValue into individual values in an array via the the split() method.
var valList = CookieValue.split(','); // ["Foo", "Bar", "Foo1", "FooFighter", "Bar2"]
If you then want the values to be assigned to individual variables, you would need to loop through the array and manually make the assignment.
Upvotes: 0
Reputation: 2617
You need to make an array from string:
CookieParams = CookieValue.split(",");
CookieParams[0] = Foo
CookieParams[1] = Bar
Upvotes: 0
Reputation: 6034
use the String.split(delimiter) method
var array = readCookie('ExCook').split(",");
Reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
Upvotes: 1