-1

I need to get the array in the string below:

"['Comedian', 'Actor']"

For example, for the above, I should get ['Comedian', 'Actor'].

Already working using eval(). Is there any other way to get the desired result?

M.K
  • 1,464
  • 2
  • 24
  • 46
SabirAmeen
  • 153
  • 9
  • possible duplicate of https://stackoverflow.com/questions/36038454/parsing-string-as-json-with-single-quotes – AZ_ Apr 10 '19 at 06:20
  • Possible duplicate of [Parsing string as JSON with single quotes?](https://stackoverflow.com/questions/36038454/parsing-string-as-json-with-single-quotes) – adiga Apr 10 '19 at 06:29

1 Answers1

4

Normally i would suggest using a JSON.parse functionality to do so, however since this is not a valid json format due to single quotes instead of double quotes you could try to first replace those and only then parse

const str = "['Comedian','Actor']";

console.log(JSON.parse(str.replace(/'/g, '"')));

or you could use JSON5

const str = "['Comedian','Actor']";
console.log(JSON5.parse(str));
<script src="https://unpkg.com/json5@^2.0.0/dist/index.min.js"></script>
Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30