Convert hex to RGB

Expand #rgb if needed and read the red, green and blue channels.

JavaScript Version 1.0.0 · MIT · .md

convert-hex-to-rgb.js
function hexToRgb(hex) { return hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`).substring(1).match(/.{2}/g).map(channel => parseInt(channel, 16)); }

Input & expected output

Input

"#1c6141"

Expected output

[
  28,
  97,
  65
]

The edge case

Input

"fff"

Expected output

[
  255,
  255,
  255
]

Know the limits

  • Accepts #rgb and #rrggbb with or without #; alpha channels are outside this contract.

The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.

Source & maintenance

Based on Convert hex to rgb from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

Validates #rgb and #rrggbb input before parsing. Original MDX retained as inert source evidence.

Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.

Local fixture scope · Node.js 22.23.2 · reviewed October 28, 2026. No external service is required.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.