Color & design
Convert a HEX Code to RGB with a Strict JavaScript Parser
Parse three-digit and six-digit HEX in JavaScript, reject malformed values and test exact RGB channels with independent examples and a reverse-conversion check.
A small HEX-to-RGB function should validate the complete input before parsing channel pairs. Otherwise a partial parse can turn a malformed string into an apparently valid color. The example below accepts only three or six hexadecimal digits, with an optional leading hash sign. It returns three decimal byte values and rejects alpha forms explicitly through the length check.
Validate, expand and parse
function hexToRgb(input) {
if (typeof input !== "string") {
throw new TypeError("Use a text HEX color");
}
let hex = input.trim().replace(/^#/, "");
if (/^[0-9a-f]{3}$/i.test(hex)) {
hex = [...hex].map(digit => digit + digit).join("");
}
if (!/^[0-9a-f]{6}$/i.test(hex)) {
throw new Error("Use three or six HEX digits");
}
return [0, 2, 4].map(offset =>
Number.parseInt(hex.slice(offset, offset + 2), 16)
);
}
The first check prevents arbitrary objects or numbers from being silently converted to strings. Trimming allows incidental whitespace around a pasted value. Removing one leading hash sign preserves the expected syntax while leaving a second hash to fail validation. The anchored regular expressions require the whole remaining value to match.
Test exact values rather than a plausible swatch
hexToRgb("#123456"); // [18, 52, 86]
hexToRgb("#abc"); // [170, 187, 204]
hexToRgb("000005"); // [0, 0, 5]
hexToRgb("#FFff00"); // [255, 255, 0]
The short form repeats each digit before parsing: abc becomes aabbcc. The leading-zero example checks that a small blue channel remains in the correct position. The mixed-case example checks that case affects notation only. Keep these expectations as exact array comparisons in a test rather than accepting any three values between zero and 255.
Reject incomplete and unsupported input
Test an empty string, #12, #12zz56, ##123456 and #12345678. Each should throw under this function's stated contract. The eight-digit value may be meaningful to another color parser, but alpha is outside this function's scope. Rejecting it clearly is preferable to silently discarding its last two digits.
Do not replace the full validation with a single parseInt call on the entire input. A parsing function can accept a numeric prefix while ignoring later invalid characters. Validation and conversion answer different questions: whether the complete string has the supported shape, and what the already validated digits represent.
Keep failure separate from the last successful result
In a live input field, catch the error at the UI boundary and display a concise input message. Clear or mark the previous output as outdated and disable any action that would copy it as the new result. Returning [0, 0, 0] on every error would make malformed input indistinguishable from a legitimate black color.
When showing the original input in an error message, assign it as text rather than inserting it as HTML. Keep validation independent of presentation: an error renderer must not interpret markup that happened to be pasted into the color field.
Use HEX to RGB as an additional check for the same accepted examples. Select HEX → RGB and compare the numeric RGB line. This is a cross-check of this bounded conversion, not a claim that the function supports every CSS color expression or named color.
Verify the reverse representation
Convert each resulting byte back to base sixteen and pad it to two digits before joining the channels. The first example must recover 123456. For shorthand input, compare against the expanded form aabbcc. This round trip catches a swapped channel order or missing zero padding even when the resulting swatch still looks plausible.
If the application later needs alpha, normalized channels or a different color space, extend the return type and tests deliberately. Do not overload an existing three-element array with a hidden convention that consumers cannot distinguish from the original opaque RGB contract.
Syntax reference
The broader CSS color syntax reference provides context for formats intentionally outside this parser.


