AniUI Academy
easy+150 XPPractice

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.

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.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.