0

I'd like to convert an string containing an array to an array.

Here's the string :

var colors = "['#e6f0ff', '#000a1a' ,'#ffe680', '#ffcc00', '#ffd9b3']";

Here's the result I want (not a string anymore) :

var colorsArray = ['#e6f0ff', '#000a1a' ,'#ffe680', '#ffcc00', '#ffd9b3'];

The double quotes will always be on the beginning and on the end, so I found this code from another post but my string still remains as string...

colors.replace(/^"(.+(?="$))"$/, '$1');

How can I achieve this and what's the best practice ?

4 Answers 4

1

Using regex

var colors = "['#e6f0ff', '#000a1a' ,'#ffe680', '#ffcc00', '#ffd9b3']";

console.log(colors.match(/#....../g))
console.log(colors.match(/#[a-f0-9]{6}/g))

Sign up to request clarification or add additional context in comments.

Comments

1

One way to do it is to use the String.match

colors.match(/(#[a-f0-9]{6})/g)

will return an array of colours

Comments

0

Replace single qoutes with double and use JSON.parse

var colorsArray = JSON.parse(colors.replace(/'/g,'"'))

1 Comment

@charlietfl You can open console and run this code. After replacing single quotes with double it works.
0

If you trust the input is safe you can use eval()

var colors = "['#e6f0ff', '#000a1a' ,'#ffe680', '#ffcc00', '#ffd9b3']",
  colorsArray = eval(colors);

console.log('colorsArray is array = ', Array.isArray(colorsArray))

Comments

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.