[英]Convert a string containing a python list to a javasctipt array
I have this string:我有这个字符串:
items = "['item1', 'item2']"项目=“['item1','item2']”
i need it to be a javascript array like this:我需要它是这样的 javascript 数组:
items = ['item1', 'item2']项目 = ['item1', 'item2']
i try this and it works:我试试这个,它有效:
items.replace("]","").replace("[","").replaceAll("'","").split(","); items.replace("]","").replace("[","").replaceAll("'","").split(",");
and the result I obtained was as expected:我得到的结果和预期的一样:
['item1', 'item2'] ['项目1','项目2']
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()
:您可以使用正则表达式文本替换和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:如果您想完全避免JSON.parse()
,我们可以微调文本替换并使用.split()
方法,如下所示:
const items = "['item1', 'item2']"; const array = items.replace(/\[|\]|\s|'/g,'').split(','); console.log(array);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.