Parse a hex colour into RGB
Design tokens arrive as hex strings, but the moment you need transparency you need the channels as numbers to build rgba(255, 136, 0, 0.5).
Implement hexToRgb(hex). It returns a plain object { r, g, b } whose values are integers from 0 to 255, or null when the input is not a valid hex colour.
Accept an optional leading #, and accept both the 6-digit form (#ff8800) and the 3-digit shorthand (#f80), where each shorthand digit is doubled so f80 means ff8800. Hex digits are case-insensitive. Surrounding whitespace is trimmed. Anything else — a non-string, an empty string, a length other than 3 or 6 after removing the #, or any character outside 0-9a-fA-F — returns null.
Arguments
hexstring- A hex colour string, with or without a leading
#, in either the 6-digit or 3-digit shorthand form. Case-insensitive and allows surrounding whitespace.
Returns
{ r: number; g: number; b: number } | null — An object of integer channel values from 0 to 255, or null when the input is not a valid hex colour.
Examples
hexToRgb("#ff8800");
// => { r: 255, g: 136, b: 0 }A standard 6-digit hex colour parses straight into channels.
hexToRgb("f80");
// => { r: 255, g: 136, b: 0 }The 3-digit shorthand doubles each digit; the leading # is optional.
hexToRgb("#12345");
// => nullAny invalid length or non-hex character returns null.
What it has to do
- Return
{ r, g, b }with integer channel values from 0 to 255. - Accept the hex string with or without a leading
#. - Expand the 3-digit shorthand by doubling each digit.
- Accept upper and lower case hex digits.
- Return
nullfor any invalid input, including wrong lengths and non-hex characters.
Notes
- The 3-digit shorthand
#f80expands by digit duplication, not by multiplication, so each short digit maps to the pairdigit + digit. - This function does not handle the 8-digit
#rrggbbaaform or the newer 4-digit shorthand; those need an alpha channel in the return type.
Stuck? The javascript course covers everything this challenge needs.
- 1.parses a six digit hex colour
- 2.expands the three digit shorthand without a hash
- 3.accepts upper case digits
- 4.returns null for a wrong length
- 5.returns null for non hex characters and for an empty string
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.