Home > Software design >  Parse string list in javascript
Parse string list in javascript

Time:08-25

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"]

CodePudding user response:

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 = []
}

CodePudding user response:

Just parse it like this:

JSON.parse(list)
  • Related