Search code examples
javascriptjavascript-objects

How to turn Javascript object value into array when the value is wrapped in quotes?


How can this javascript object value that is a string be converted into an array, removing the outer quotes, leaving just the brackets? The attempt of using obj["text-font"] = obj["text-font"].split('"').join(""); was not successful.

Current

text-font: "['Open Sans Regular', 'Arial Unicode MS Regular']"

Intended

text-font: ['Open Sans Regular', 'Arial Unicode MS Regular']

Solution

  • If you know there are no other quotes in the strings other than the ones that delimit the font names, you can convert them to double quotes and then use JSON.parse() to convert it to an array.

    obj['text-font'] = JSON.parse(obj['text-font'].replace(/'/g, '"'));