Search code examples
javascriptarraysjsonstring-parsing

Javascript Trying to parse string into an array


I am having a variable which stores a string like this

var colorArr="['#3f67c5', '#cb4728', '#f19d39', '#459331', '#984830', '#8C2094']"

I am trying to convert this string into an array by

var result = JSON.parse(colorArr)

But I keep on getting the following error "SyntaxError: Unexpected token ' in JSON at position 1

Is there a way by which I can convert this string into a proper array?

Thanks in advance


Solution

  • Use single quotes and put double quotes inside of it

    var colorArr= '["#3f67c5", "#cb4728", "#f19d39", "#459331", "#984830", "#8C2094"]';
    
    var result = JSON.parse(colorArr)
    
    console.log(result)