3

I want to implement a counter for unique articles visited in my website, basically storing the ids of the articles the user has visited in a cookie. My issue is that the recovered value is, of course, a string. How would you convert a string that looks like this "['test','b','c']" to an array? Using eval is not advised, right?

0

3 Answers 3

5

Use JSON.parse to turn a string into an array:

const string = '["test","b","c"]';
const arr = JSON.parse(string);
console.log(arr[0]);

Note that you need to have proper JSON formatting, though - keys and non-numeric values need to have double quotes. Easiest to serialize automatically with JSON.stringify:

const arr = ["test","b","c"];
const str = JSON.stringify(arr);
console.log(str);

If you absolutely cannot change the single-quotes in the string you're working with originally, then use replace to turn it into something parseable:

const str = "['test','b','c']";
const jsonFormattedStr = str.replace(/'/g, '"');
const arr = JSON.parse(jsonFormattedStr);
console.log(arr[1]);

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

5 Comments

JSON.parse won't work on the string provided by OP, though.
Right, which is why he should be using JSON.stringify to take care of the formatting problems automatically.
Not sure that makes sense. He said he can only get the array as a string initially. JSON.stringify is used to convert objects to strings, not cleanup formatting problems.
you could replace the ' with " and then parse it (to work with the OP) JSON.parse(string.replace(new RegExp('\'', 'g'), '"'));
As I am also searching for a solution, sadly the replace() fails in ['test "one"','b','c']
1

While using JSON.parse() is the correct way to convert data strings to usable objects, the string in your question is not valid JSON syntax. Namely the single quotes will result in an unexpected token error.

If your only issue is the quotes, then it becomes trivial to prepare your data for parsing:

var str = "['test','b','c']"
// convert to double quotes
str = str.split('\'').join('"')
// now parse
var arr = JSON.parse(str)
console.log(arr)

Comments

1

You need to convert the quotes to double quotes, and then use JSON.parse

let string = "['test','b','c']";
// replace quotes with double quotes
let stringFixed = string.replace(/'/g, '"');
// parse the string
let result = JSON.parse( stringFixed );

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.