Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

How to convert a string into an array in JavaScript

Nouman Abbasi

In this shot, we will cover how to convert a string into an array in JavaScript.

Method 1: Using JSON.parse()

Let’s say you have the following string:

"[0,1,2]"

You can easily convert it into a JavaScript array using JSON.parse():

JSON.parse("[0,1,2]") // [0,1,2]

Code

let stringArray = "[0,1,2]";

let array = JSON.parse(stringArray);

console.log(array);

JSON.parse() will throw an exception if the string representation of the array is incorrect.

The above method works great for simple arrays, but it fails if you have an array of strings. One workaround is to escape the quotation marks as "[\"a\",\"b\"]"; or, you can try the second method below.

Method 2: Using split()

The split() method can be used to split a string based on the separator provided and return an array of substrings.

This method works better if you want to create an array of strings.

let stringArray = "a,b,c";

let array = stringArray.split(",")

console.log(array);

RELATED TAGS

javascript

CONTRIBUTOR

Nouman Abbasi
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring