If I have the string rgba(111,222,333,0.5)
how can i extract the individual colours from the string, i.e.
JavaScript
x
5
1
red => 111
2
green => 222
3
blue => 333
4
opacity => 0.5
5
I would like to be able to use a neat clean solution for this so I am assuming a regular expression would be best?
Advertisement
Answer
I’d avoid regex for a predictable string, and suggest:
JavaScript
1
28
28
1
// assigning the rgb() colour to a variable:
2
var colorString = "rgba(111,222,333,0.5)",
3
4
// using String.prototype.substring() to retrieve
5
// the substring between the indices of the opening
6
// and closing parentheses:
7
colorsOnly = colorString.substring(
8
// here we find the index of the opening
9
// parenthesis, and add 1 to that index
10
// so that the substring starts after that
11
// parenthesis:
12
colorString.indexOf('(') + 1,
13
14
// and terminating the substring at the
15
// index of the closing parenthesis:
16
colorString.lastIndexOf(')')
17
// here we split that substring on occurrence
18
// of a comma followed by zero or more white-
19
// space characters:
20
).split(/,s*/),
21
22
// String.prototype.split() returns an Array,
23
// here we assign those Array-elements to the
24
// various colour-, or opacity-, variables:
25
red = colorsOnly[0],
26
green = colorsOnly[1],
27
blue = colorsOnly[2],
28
opacity = colorsOnly[3];
Or, given that you want an object returned:
JavaScript
1
12
12
1
var colorString = "rgba(111,222,333,0.5)",
2
colorsOnly = colorString.substring(colorString.indexOf('(') + 1, colorString.lastIndexOf(')')).split(/,s*/),
3
// here we initialise an empty Object:
4
components = {};
5
// here we assign the Array-elements to the
6
// named properties of that Object:
7
components.red = colorsOnly[0];
8
components.green = colorsOnly[1];
9
components.blue = colorsOnly[2];
10
components.opacity = colorsOnly[3];
11
12
console.log(colorsOnly, components);
Edited to use more contemporary JavaScript:
JavaScript
1
14
14
1
const colorString = "rgba(111,222,333,0.5)",
2
// here we use destructuring assignment to assign the returned Array-elements
3
// - in respective order - to the named variables:
4
[red, green, blue, opacity] = colorString.substring(colorString.indexOf('(') + 1, colorString.lastIndexOf(')')).split(/,s*/),
5
// passing the variables into the Object Literal; in this instance
6
// we're passing in the variables which are the literal name of the
7
// properties they define and which also contain the relevant value:
8
colorObject = {
9
red,
10
green,
11
blue,
12
opacity
13
};
14
console.log(red, green, blue, opacity, colorObject);
References: