4

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?

Martin V
  • 45
  • 4
  • 7
    easiest way: `eval(items)` or `JSON.parse(items.replace(/'/g, '"'))` –  Apr 29 '21 at 15:27
  • 1
    Required reading for `eval`: https://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil – Pranav Hosangadi Apr 29 '21 at 15:42
  • 2
    Yeah, don't use `eval`, but `JSON.parse` is the way to go for stuff like this. – Nisala Apr 29 '21 at 16:35
  • @MartinV please check my solution when you have a chance. It uses a regex expression to make the replacement simpler and then `JSON.parse()` to interpret the final result as JSON data. – Brandon McConnell Apr 29 '21 at 18:41
  • @ChrisG eval(items) was the solution!, thank you! – Martin V Apr 29 '21 at 20:46
  • *The question is: can the same be done in a simpler way?* - if you can change the Python side, instead of just stringifying your list, use [`json.dumps()`](https://docs.python.org/3/library/json.html). – tevemadar Dec 16 '21 at 21:24

1 Answers1

2

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);
Brandon McConnell
  • 5,776
  • 1
  • 20
  • 36