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 ?

asked May 21, 2017 at 12:05

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

answered May 21, 2017 at 12:10
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

answered May 21, 2017 at 12:09

Comments

0

Replace single qoutes with double and use JSON.parse

var colorsArray = JSON.parse(colors.replace(/'/g,'"'))
answered May 21, 2017 at 12:08

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

answered May 21, 2017 at 12:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.