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']
4
  • 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) Commented May 28, 2021 at 19:53
  • 1
    Why are you using split('"')? There are no " characters in the string. Commented May 28, 2021 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. Commented May 28, 2021 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 Commented Jun 7, 2021 at 16:35

3 Answers 3

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, '"'));
Sign up to request clarification or add additional context in comments.

Comments

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()

2 Comments

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!
You're right. Thanks for the comments. I've now corrected the mistake.
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.

2 Comments

At least include a banner with the drawbacks and security vulnerabilites of eval before mentioning it in an answer!
@FZs - good point, done. Feel free to elaborate more on it if desired.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.