In this shot, we will cover how to convert a string into an array in JavaScript.
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]
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.
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);
Free Resources