0

I have a cookie set up which has data stored in the following format:

{"g":"776","f":"88876","hit":"true","TESTVALUE":"this is the value i want to capture"}

I want to capture "TESTVALUE" in its own variable.

I am using this script to actually capture the cookie data (where the cookie is called "chocolateChip":

var getCookie = function (name) {
    var re = new RegExp(name + "=([^;]+)");
    var value = re.exec(document.cookie);
    return (value != null) ? unescape(value[1]) : null;
} // code indentation

var cookie = getCookie(chocolateChip);

Im then using the following script to pass the "testvalue" string to its own variable:

var test = cookie.TESTVALUE;

However this does not seem to work.

0

1 Answer 1

2

The cookie value is a JSON string, which you need to parse to get an actual JS object.

Try this:

var cookie = getCookie(chocolateChip);
var test = JSON.parse(cookie).TESTVALUE;

Or, if you need to access more properties:

var cookie = getCookie(chocolateChip);
var cookieObject = JSON.parse(cookie);
var testValue = cookieObject.TESTVALUE;
Sign up to request clarification or add additional context in comments.

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.