javascript 40 lines · 7 steps

Parsing hex colors into RGBA channels

Normalize any 3-, 4-, 6-, or 8-digit hex string, then bit-shift it into red, green, blue, and alpha values.

Explained by highlit
1function parseHexColor(hex) {
2 const cleaned = hex.trim().replace(/^#/, '');
3 
4 const expand = (short) =>
5 short
6 .split('')
7 .map((ch) => ch + ch)
8 .join('');
9 
10 let normalized;
11 switch (cleaned.length) {
12 case 3:
13 normalized = expand(cleaned) + 'ff';
14 break;
15 case 4:
16 normalized = expand(cleaned);
17 break;
18 case 6:
19 normalized = cleaned + 'ff';
20 break;
21 case 8:
22 normalized = cleaned;
23 break;
24 default:
25 throw new Error(`Invalid hex color: ${hex}`);
26 }
27 
28 if (!/^[0-9a-fA-F]{8}$/.test(normalized)) {
29 throw new Error(`Invalid hex color: ${hex}`);
30 }
31 
32 const value = parseInt(normalized, 16);
33 
34 return {
35 r: (value >>> 24) & 0xff,
36 g: (value >>> 16) & 0xff,
37 b: (value >>> 8) & 0xff,
38 a: Number(((value & 0xff) / 255).toFixed(3)),
39 };
40}
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1Reducing many input shapes to one canonical form keeps the rest of the logic simple.
  2. 2Bit shifts with unsigned masks extract fixed-width fields from a packed integer cleanly.
  3. 3Validating the normalized value after transformation catches bad input regardless of its original length.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing hex colors into RGBA channels — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code