Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert Array-like String to Array

I have a string that looks like an array: "[918,919]". I would like to convert it to an array, is there an easier way to do this than to split and check if it is a number? Thanks

like image 560
Ace Dimasuhid Avatar asked Mar 24 '13 06:03

Ace Dimasuhid


2 Answers

Use JSON.parse.

var myArray = JSON.parse("[918,919]");
like image 65
ShuklaSannidhya Avatar answered Sep 19 '22 16:09

ShuklaSannidhya


You can get rid of the brackets at the beginning and the end, then use:

str.split(",")

which will return an array split by the comma character.

EDIT

var temp = new Array();
temp = "[918,919]".slice( 1, -1).split(",");
for (a in temp ) {
temp[a] = parseInt(temp[a]);
}
like image 39
Jsdodgers Avatar answered Sep 17 '22 16:09

Jsdodgers