I have a string that looks like an array: "[918,919]". I would like to convert it to an array, is there an easier way to do this than to split and check if it is a number? Thanks
-
I guess no easier way without split and check.Abubakkar– Abubakkar2013-03-24 06:40:33 +00:00Commented Mar 24, 2013 at 6:40
Add a comment
|
3 Answers
If you use JSON.parse the string must have " and not ' otherwise the code will fail.
for example:
let my_safe_string = "['foo','bar',123]";
let myArray = JSON.parse(my_safe_string)
the code will fail with
Uncaught SyntaxError: Unexpected token ' in JSON at position 1
instead if you use " all will work
let my_safe_string = "["foo","bar",123]";
let myArray = JSON.parse(my_safe_string);
so you have two possibility to cast string array like to array:
- Replace ' with "
my_safe_string.replace("'",'"');and after doJSON.parse - If you are extremely sure that your string contain only string array you can use eval:
example:
let myArray = eval(my_safe_string );