Given a string of a valid CSS color value:
- #fff
- #ffffff
- white
- rgb(255, 255, 255)
I need to get an array of numbers of the following format: [R, G, B]
What is the most efficient way of doing this in JavaScript (assuming a major browser)?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Obviously, the numeric values will be easier to parse than names. So we do those first.
That’s one. Now for the full six-digit format:
And now for
rgb()format:Optionally, you can also add support for
rgbaformat, and evenhsl/hslaif you add an HSL2RGB conversion function.Finally, the named colours.
And close the function:
Actually, I don’t know why I bothered writing all that. I just noticed you specified “assuming a major browser”, I’m assuming that also means “up-to-date”? If so…
An up-to-date browser will convert any given colour to
rgb()format in its computed style. Just get it back, and read it out.