0

I have a string which is a list of ints, and I need to parse it into a list of those ints. In other words, how to convert "[2017,7,18,9,0]" to [2017,7,18,9,0]?

more info

When i console.log(typeof [2017,7,18,9,0], [2017,7,18,9,0] ), I get: string [2017,7,18,9,0]. I need to convert it into a list such that doing console.log(), i get: object Array [ 2017, 7, 18, 9, 0 ].

Thanks in advance for any help!

mahan
  • 12,366
  • 5
  • 48
  • 83

5 Answers5

5

You can use .match() with RegExp /\d+/, .map() with parameter Number

var res = "[2017,7,18,9,0]".match(/\d+/g).map(Number)
guest271314
  • 1
  • 15
  • 104
  • 177
4

You can try parsing it as JSON:

console.log(JSON.parse("[2017,7,18,9,0]"))

Or you could try to manually parse the string:

var str = "[2017,7,18,9,0]";
str = str.substring(1, str.length - 1); // cut out the brackets
var list = str.split(",");
console.log(str);
Lukas Bach
  • 3,559
  • 2
  • 27
  • 31
2

var yourString = "[2017,7,18,9,0]";
var stringArray = JSON.parse(yourString);
console.log( JSON.stringify(stringArray), typeof stringArray);

Is it JSON.parse that you need?

Jarek Kulikowski
  • 1,399
  • 8
  • 9
1

By splitting with regex (because who doesn't love a regex):

var array = "[2017,7,18,9,0]".split(/\,|\[|\]/).shift().pop();

The shift and pop remove the empty strings from the front and back of the array, which are from the open and close brackets.

M. Davis
  • 669
  • 2
  • 10
  • 17
0

These solutions are turning into a list of every available option. So in that spirit I'll throw eval() into the mix.

eval("[2017, 23, 847, 4]");

NOTE: the other answers are much better and this method should not be used.

var strArray = "[2017, 23, 847, 4]";

var realArray = eval(strArray);

console.log(realArray);
Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184