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

snippet
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("");
}