简体   繁体   English

如何将String转换为数组,并在Javascript中删除引号?

[英]How to convert String to array, and remove quotation marks in Javascript?

I want to convert the following String to an array: 我想将以下String转换为数组:

str = " ['GHR',  15, 14    ], ['GHR',  12, 20  ] ";
array = new Array (str);

when I do : console.log(array ); 当我这样做:console.log(array);

it gives me: [" ['GHR', 15, 14 ], ['GHR', 12, 20 ] "] , 它给了我:[“['GHR',15,14],['GHR',12,20]”,

but I want the result without quotation marks like: 但我希望结果没有引号,如:

[['GHR', 15, 14 ], ['GHR', 12, 20 ]] [['GHR',15,14],['GHR',12,20]]

Kindly, how to remove only the first and last quotation marks from the beginning and the end of the array? 那么,如何从数组的开头和结尾只删除第一个和最后一个引号? I'm using this method to get data from mongodatabse then convert the results to rows that google charts can read them, in Metero platform 我正在使用此方法从mongodatabse获取数据,然后将结果转换为谷歌图表可以读取的行,在Metero平台中

You can use JSON.parse which will require you to swap out the single quotes 您可以使用JSON.parse,这将要求您交换单引号

var str = " ['GHR',  15, 14    ], ['GHR',  12, 20  ] ";
var arr = JSON.parse("[" + str.replace(/'/g,'"') + "]");

or you can use new Function 或者您可以使用新功能

var str = " ['GHR',  15, 14    ], ['GHR',  12, 20  ] ";
var arr = (new Function( "return [" + str + "]")());

Or get whatever is outputting it to make an array to start with or make it valid JSON so it can be parsed correctly. 或者获取输出它的任何内容以使数组开始或使其成为有效的JSON,以便可以正确解析它。

Try below 试试以下

 var str = " ['GHR', 15, 14 ], ['GHR', 12, 20 ] "; str = str.replace(/\\s+/g, ' '); var arr = str.split('],').join(']|').split('|'); console.log(arr); 

Fiddle: http://jsfiddle.net/zo3yvqbL/1/ 小提琴: http//jsfiddle.net/zo3yvqbL/1/

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

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