AniUI Academy

Parse a hex colour into RGB

easyDOM & Utilities+150 XPPractice

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");
// => null

Any 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 null for any invalid input, including wrong lengths and non-hex characters.

Notes

  • The 3-digit shorthand #f80 expands by digit duplication, not by multiplication, so each short digit maps to the pair digit + digit.
  • This function does not handle the 8-digit #rrggbbaa form or the newer 4-digit shorthand; those need an alpha channel in the return type.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.