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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Reducing many input shapes to one canonical form keeps the rest of the logic simple.
- 2Bit shifts with unsigned masks extract fixed-width fields from a packed integer cleanly.
- 3Validating the normalized value after transformation catches bad input regardless of its original length.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-hex-colors-into-rgba-channels-explained-javascript-277a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.