Horai Nuri
Horai Nuri

Reputation: 5578

How to convert an array in a string to an array on Javascript?

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 ?

Upvotes: 0

Views: 72

Answers (4)

maurycy
maurycy

Reputation: 8465

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

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

will return an array of colours

Upvotes: 1

charlietfl
charlietfl

Reputation: 171679

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

Upvotes: 0

Priyesh Kumar
Priyesh Kumar

Reputation: 2857

Using regex

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

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

Upvotes: 1

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

Replace single qoutes with double and use JSON.parse

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

Upvotes: 0

Related Questions