Hex and RGB Color Conversion Utilities
Parse three- and six-digit hex colors into RGB channels and convert validated RGB objects back to lowercase hex strings.
Code
export function hexToRgb(hex) {
if (typeof hex !== "string") throw new TypeError("hex must be a string");
const normalized = hex.trim().replace(/^#/, "");
const expanded = normalized.length === 3
? normalized.split("").map((char) => char + char).join("")
: normalized;
if (!/^[0-9a-fA-F]{6}$/.test(expanded)) {
throw new RangeError("invalid hex color");
}
const value = Number.parseInt(expanded, 16);
return { r: (value >> 16) & 255, g: (value >> 8) & 255, b: value & 255 };
}
export function rgbToHex(color) {
if (color === null || typeof color !== "object") {
throw new TypeError("color must be an object");
}
const channels = [color.r, color.g, color.b];
for (const channel of channels) {
if (!Number.isInteger(channel) || channel < 0 || channel > 255) {
throw new RangeError("RGB channels must be integers between 0 and 255");
}
}
return "#" + channels.map((channel) => channel.toString(16).padStart(2, "0")).join("");
}Inside the snippet
Hex and RGB Color Conversion Utilities is built around the functions hexToRgb and rgbToHex.
Iteration happens inside for (const channel of channels) — everything outside it runs once. Invalid states are rejected up front: it throws TypeError and RangeError instead of continuing with bad data.
The return value is newly constructed — inputs are never handed back.
What to watch for
- The guard
typeof hex !== "string"short-circuits the flow with an earlythrowwhen its condition holds.
Using it
The entry-point signature is export function hexToRgb(hex)
hexToRgb is what another module would consume; nothing else here is load-bearing for callers.
Key statements
return "#" + channels.map((channel) => channel.toString(16).padStart(2, "0")).join("");
if (typeof hex !== "string") throw new TypeError("hex must be a string");
return { r: (value >> 16) & 255, g: (value >> 8) & 255, b: value & 255 };
Interactive Tools for This Topic
CSS Color ConverterConvert colors between HEX, rgb(), and hsl() instantly, with support for shorthand hex and rgb or hsl inputs. Fully offline and dependency free.RGBA / Hex Color ConverterConvert colors between #RRGGBB, #RRGGBBAA, rgb(), and rgba() forms with alpha handling and validation.A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.
FAQ
- Does `hexToRgb` modify its input?
- No — a new value is constructed for the result and the arguments are never written to.
- What happens on invalid input?
- `TypeError` and `RangeError` is raised at the guard (`typeof hex !== "string"`), so invalid state never reaches the main logic.
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `hexToRgb`, `rgbToHex` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.