Let’s say you have the following string:
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.
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);
View all Courses