繁体   English   中英

如何在node.js中将像数组一样的数组转换为数组?

[英]How to convert an array like string to array in node.js?

其实我在node.js从android设备获得了arraylist 但由于它是字符串形式,所以我想将其转换为array 为此我在SO引用了很多类似的问题,但没有一个是有用的。 我也尝试使用JSON.parse()但它没有帮助。

我正在以'[艺术,摄影,写作]的形式获得socialList。那么如何将这种格式转换为数组呢?

码:

var soc_arr=JSON.parse(data.societyList)
            console.log(soc_arr.length)

使用这样的东西

var array = arrayList.replace(/^\[|\]$/g, "").split(", ");

更新:

在@drinchev建议使用正则表达式之后。

正则表达式匹配char以'['开头并以']结尾

此字符串无效JSON,因为它不使用""来表示字符串。

最好的方法是使用下面的方法自己解析它:

 let data = '[test1, test2, test3]'; let parts = data .trim() // trim the initial data! .substr(1,data.length-2) // remove the brackets from string .split(',') // plit the string using the seperator ',' .map(e=>e.trim()) // trim the results to remove spaces at start and end console.log(parts); 

RegExp.match()也许吧

  console.log('[Art, Photography, Writing]'.match(/\\w+/g)) 

所以match()适用于任何字符串,并将其拆分为数组元素。

使用replacesplit 此外,使用trim()从数组元素中删除尾随和前导空格。

 var str = '[Art, Photography, Writing]'; var JSONData = str.replace('[','').replace(']','').split(',').map(x => x.trim()); console.log(JSONData); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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