简体   繁体   中英

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM