0

i have a string containg an array. i can convert it using loop over string with different conditions but that will be slow. so is there any direct way to convert string which has array in it to an actuall array? my javascript string looks like this

arr_str = '["value1", "value2", "value3"]'

i want to convert it in array something like this

arr = ["value1", "value2", "value3"]
  • 3
    `JSON.parse(arr_str)` – Zac Anger Jan 08 '23 at 19:56
  • 1
    use [JSON.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) – Cid Jan 08 '23 at 19:57
  • in my case its not working. the error is Unexpected token ''', "['500', 'Large']" is not valid JSON – Sajawal Sheraz Jan 08 '23 at 20:05
  • i have to do something like this: let arr_str = obj.innerHTML; let arr = JSON.parse(arr_str); – Sajawal Sheraz Jan 08 '23 at 20:08
  • 1
    You can do it like this: `JSON.parse("['500', 'Large']".replaceAll("'", '"'))` https://stackoverflow.com/questions/22101353/json-parse-error-is-giving-error-with-double-quotes-string JSON has a strict quotation marks spec, so you need to switch them in your string. – R. Vait Jan 08 '23 at 20:15

0 Answers0