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?

3
  • 1
    And would the expected result be an array with just the two values 11 and 66 (hint: it is valid JSON) ? Commented Nov 14, 2019 at 22:24
  • Alternatively, '[1, 2]'.substring(1, s.length - 1).split(', ').map(str => +str) also works, but is less robust than JSON.parse. Commented Nov 14, 2019 at 22:27
  • Please refer to the following link, it can be very useful. stackoverflow.com/questions/3413586/… Commented Nov 14, 2019 at 22:41

3 Answers 3

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]
Sign up to request clarification or add additional context in comments.

Comments

2

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

var array = JSON.parse(str);

Comments

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.