-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.

5 Answers 5

1

use the String.split(delimiter) method

var array = readCookie('ExCook').split(",");

Reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quick response. 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.
0

You need to make an array from string:

CookieParams = CookieValue.split(",");
CookieParams[0] = Foo
CookieParams[1] = Bar

Comments

0

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.

1 Comment

or as cyborg86pl shows... it the list is small enough, skip the loop and directly assign to variables. Now if the list will be an arbitrary length with no or a large max, then we whip out the loop.
0

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.

2 Comments

what is readCookie('in your example
It's in the question, a function that reads a cookie I assume.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.