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
javascript
const express = require('express'); const app = express();
Enforcing HTTPS with Express middleware
middleware
https
security
Intermediate
6 steps
rust
use std::time::Duration; #[derive(Debug, PartialEq)] pub enum ParseDurationError {
Parsing duration strings safely in Rust
parsing
error-handling
checked-arithmetic
Intermediate
8 steps
go
package logparse import ( "bufio"
Splitting multi-line logs with a Scanner
parsing
streaming
bufio
Intermediate
9 steps
typescript
type TokenType = "keyword" | "string" | "comment" | "number" | "text"; interface Token { type: TokenType;
How a regex tokenizer highlights code
tokenizer
regex
lexing
Intermediate
10 steps
javascript
const express = require('express'); const router = express.Router(); router.get('/articles/:slug', async (req, res, next) => {
Conditional GET caching in Express
http-caching
conditional-get
routing
Intermediate
8 steps
java
public final class LogRedactor { private static final Pattern SECRET = Pattern.compile( "(?i)(password|token|api[_-]?key|secret|authorization)\\s*[=:]\\s*\\S+");
Streaming log redaction in Java
regex
streaming-io
try-with-resources
Intermediate
9 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.