Skip to content

hexToRgb

Parses a hex color string (#rgb, #rgba, #rrggbb, #rrggbbaa — the leading # is optional) into its RGB(A) channels.

Available since v3.0.0

import { hexToRgb } from '@helpers4/color';
// or, from the all-in-one package (same code, one install):
import { hexToRgb } from 'helpers4/color';
hexToRgb(hex: string): RgbColor | null
ParameterTypeDescription
hexstringThe hex color string to parse

RgbColor | null — The parsed color, or null if hex is not a valid hex color

The leading # is optional; shorthand 3/4-digit forms are also supported.

hexToRgb('#ff0000')
// => { r: 255, g: 0, b: 0, a: 1 }

Lets you branch on parse failure instead of getting a garbage color.

hexToRgb('not-a-color')
// => null

An RGB(A) color with channels expressed as plain numbers, convenient for further conversion or manipulation.

interface RgbColor {
  a?: number;
  b: number;
  g: number;
  r: number;
}

View source on GitHub