3

How to transform a string of this format '[11, 66]' to an array ?

Array.isArray('[11, 66]') return false since it's considered as string?

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
user2222
  • 444
  • 2
  • 8
  • 18
  • 1
    And would the expected result be an array with just the two values `11` and `66` (hint: it is valid JSON) ? – adeneo Nov 14 '19 at 22:24
  • Alternatively, `'[1, 2]'.substring(1, s.length - 1).split(', ').map(str => +str)` also works, but is less robust than `JSON.parse`. – mario_sunny Nov 14 '19 at 22:27
  • Please refer to the following link, it can be very useful. https://stackoverflow.com/questions/3413586/string-to-string-array-conversion-in-java – Dawit Tilahun Davatron Nov 14 '19 at 22:41

3 Answers3

4

A good way to do this would be JSON.parse.

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

In your example:

JSON.parse('[11, 66]')

Output:

[11, 66]
Andrew
  • 763
  • 7
  • 21
Cam
  • 14,930
  • 16
  • 77
  • 128
2

If the string is a valid JSON string, then use JSON.parse:

var array = JSON.parse(str);
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
1

Did you try to use JSON API ?

JSON.parse(string); // turn a JSON string into a plain object (or an array as your example)
JSON.stringify(object); // turn an object (or an array) into JSON string

Also work for arrays!