-1

I have a string in this format: "['A', 'B', 'C']". I want to convert it to an array ['A', 'B', 'C']. I tried using JSON.parse() but it did not work. Any help would be appreciated.

const strArray = "['A', 'B', 'C']";
const parsedString = JSON.parse(strArray);
console.log(parsedString);
Miroslav Glamuzina
  • 4,472
  • 2
  • 19
  • 33
Nikhil
  • 27
  • 4

3 Answers3

0

Convert the string to a valid json by replacing the single quotes with double quotes and parse:

const str = "['A', 'B', 'C']";

const result = JSON.parse(str.replace(/'/g, '"'));

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

The actual solution would be to change the format of your datasource to be valid JSON(" instead of '):

 JSON.parse('["A", "B", "C"]')

However, if that is not an option, you can do that programmaticaly for sure:

JSON.parse("['A', 'B', 'C']".replace(/'/, '"'))
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
-1
let string = "['A', 'B', 'C']";
JSON.parse(string.replace(/'/g, '"'))

The error with JSON.parse is because JSON requires " and not '

junvar
  • 11,151
  • 2
  • 30
  • 46