If I have the string rgba(111,222,333,0.5) how can i extract the individual colours from the string, i.e.
red => 111 green => 222 blue => 333 opacity => 0.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:
// assigning the rgb() colour to a variable:
var colorString = "rgba(111,222,333,0.5)",
// using String.prototype.substring() to retrieve
// the substring between the indices of the opening
// and closing parentheses:
colorsOnly = colorString.substring(
// here we find the index of the opening
// parenthesis, and add 1 to that index
// so that the substring starts after that
// parenthesis:
colorString.indexOf('(') + 1,
// and terminating the substring at the
// index of the closing parenthesis:
colorString.lastIndexOf(')')
// here we split that substring on occurrence
// of a comma followed by zero or more white-
// space characters:
).split(/,s*/),
// String.prototype.split() returns an Array,
// here we assign those Array-elements to the
// various colour-, or opacity-, variables:
red = colorsOnly[0],
green = colorsOnly[1],
blue = colorsOnly[2],
opacity = colorsOnly[3];Or, given that you want an object returned:
var colorString = "rgba(111,222,333,0.5)",
colorsOnly = colorString.substring(colorString.indexOf('(') + 1, colorString.lastIndexOf(')')).split(/,s*/),
// here we initialise an empty Object:
components = {};
// here we assign the Array-elements to the
// named properties of that Object:
components.red = colorsOnly[0];
components.green = colorsOnly[1];
components.blue = colorsOnly[2];
components.opacity = colorsOnly[3];
console.log(colorsOnly, components);Edited to use more contemporary JavaScript:
const colorString = "rgba(111,222,333,0.5)",
// here we use destructuring assignment to assign the returned Array-elements
// - in respective order - to the named variables:
[red, green, blue, opacity] = colorString.substring(colorString.indexOf('(') + 1, colorString.lastIndexOf(')')).split(/,s*/),
// passing the variables into the Object Literal; in this instance
// we're passing in the variables which are the literal name of the
// properties they define and which also contain the relevant value:
colorObject = {
red,
green,
blue,
opacity
};
console.log(red, green, blue, opacity, colorObject);References: