Skip to content

hexToRgb

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

Available since next

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

View source on GitHub