Martin V
Martin V

Reputation: 35

Convert a string containing a python list to a javasctipt array

I have this string:

items = "['item1', 'item2']"

i need it to be a javascript array like this:

items = ['item1', 'item2']

i try this and it works:

items.replace("]","").replace("[","").replaceAll("'","").split(",");

and the result I obtained was as expected:

['item1', 'item2']

The question is: can the same be done in a simpler way?

Upvotes: 3

Views: 83

Answers (1)

Brandon McConnell
Brandon McConnell

Reputation: 6119

You can accomplish this very simply using a regex text replacement and JSON.parse():

const items = "['item1', 'item2']";

const array = JSON.parse(items.replace(/'/g, '\"'));

console.log(array);

If you would like to avoid JSON.parse() altogether, we can fine-tune the text replacement and use the .split() method like this:

const items = "['item1', 'item2']";

const array = items.replace(/\[|\]|\s|'/g,'').split(',');

console.log(array);

Upvotes: 2

Related Questions