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
Horai Nuri
5,59818 gold badges86 silver badges138 bronze badges
4 Answers 4
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
Priyesh Kumar
2,8571 gold badge17 silver badges29 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
maurycy
8,4201 gold badge30 silver badges44 bronze badges
Comments
Replace single qoutes with double and use JSON.parse
var colorsArray = JSON.parse(colors.replace(/'/g,'"'))
answered May 21, 2017 at 12:08
Yury Tarabanko
45.1k10 gold badges88 silver badges99 bronze badges
1 Comment
Yury Tarabanko
@charlietfl You can open console and run this code. After replacing single quotes with double it works.
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
charlietfl
172k14 gold badges125 silver badges154 bronze badges
Comments
lang-js