0

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']
ckingchris
  • 559
  • 1
  • 12
  • 25
  • 2
    It would be easier if your string was valid JSON (with double quotes, not single ones). Then you could just do: `JSON.parse(str)` – blex May 28 '21 at 19:53
  • 1
    Why are you using `split('"')`? There are no `"` characters in the string. – Barmar May 28 '21 at 19:53
  • 3
    Where is this coming from? Maybe you can fix the source to generate a normal array or valid JSON, instead of this nonstandard format. – Barmar May 28 '21 at 19:57
  • @Barmar went back and fixed the source, sending over a string with items separated by commas then used obj["text-font"].split(", "); thanks for the suggestion – ckingchris Jun 07 '21 at 16:35

3 Answers3

5

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, '"'));
Barmar
  • 741,623
  • 53
  • 500
  • 612
3

You can replace the single quotes with double ones and then use JSON.parse() to convert it into an actual Array of Strings.

obj["text-font"] = JSON.parse(obj["text-font"].replaceAll("'",'"'))

Have a look here for more information: MDN Web Docs: JSON.parse()

maweil
  • 91
  • 4
  • The problem is that the array elements are between single brackets **'** instead of double **"**, which is why the JSON.parse won't work. It's good measure to test your solution before replying so you can give better answers in the future! – Rafael de Freitas May 28 '21 at 19:59
  • 1
    You're right. Thanks for the comments. I've now corrected the mistake. – maweil May 28 '21 at 20:00
1

perhaps use eval() ** though be aware of the security concerns, see below

let obj = {
  "text-font": "['Open Sans Regular', 'Arial Unicode MS Regular']"
}

console.log(eval(obj['text-font']))

// to fix the object

obj['text-font'] = eval(obj['text-font']);
console.log(obj)

eval() has security risks and malicious users can use the in-browser debugger to execute their own javascript through XSS attacks - the general advice is not to use it recklessly.

Kinglish
  • 23,358
  • 3
  • 22
  • 43
  • 1
    ***At least*** include a banner with the drawbacks and security vulnerabilites of `eval` before mentioning it in an answer! – FZs May 28 '21 at 20:03
  • 1
    @FZs - good point, done. Feel free to elaborate more on it if desired. – Kinglish May 28 '21 at 20:10