0

So when I retrieve a cookie in javascript I get it like this

"[\"name\"\054 \"name1\"\054 \"name2\"\054 \"name3\"\054 \"name4\"\054 \"name5\"]"

How to change it to be a list as below?

["name", "name1", "name2", "name3", "name4", "name5"]

2 Answers 2

3
const parsed = JSON.parse("[\"name\"\054 \"name1\"\054 \"name2\"\054 \"name3\"\054 \"name4\"\054 \"name5\"]");

console.log(parsed); // ["name", "name1", "name2", "name3", "name4", "name5"]

Your cookie was stored as a JSON string, so when you retrieve it you need to use JSON to turn it back into an array (a list). Make sure it isn't null first, though:

if (typeof retrievedCookie == "string") {
  var myArray = JSON.parse(retrievedCookie)
} else {
  // retrievedCookie is probably null or undefined
  var myArray = []
}
Sign up to request clarification or add additional context in comments.

1 Comment

"JavaScript cookies are stored as JSON strings": that is not accurate. It happens to be the case here, but depends on what was written to the cookie. It could be JSON, it could be any other kind of formatted string.
1

Just parse it like this:

JSON.parse(list)

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.