Yousef
Yousef

Reputation: 139

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

I want to convert the following String to an array:

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

when I do : console.log(array );

it gives me: [" ['GHR', 15, 14 ], ['GHR', 12, 20 ] "] ,

but I want the result without quotation marks like:

[['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

Upvotes: 2

Views: 3404

Answers (2)

Anand G
Anand G

Reputation: 3210

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/

Upvotes: 0

epascarello
epascarello

Reputation: 207527

You can use JSON.parse which will require you to swap out the single quotes

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.

Upvotes: 4

Related Questions