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.

JavascriptData Integrity

Code

javascriptsnippet
25 lines
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 early throw when 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

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.