Convert hex to RGB
Expand #rgb if needed and read the red, green and blue channels.
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.
Keep exploring
- Convert Celsius to Fahrenheit — Apply the temperature conversion without rounding the result.
- Convert URL parameters to object — Read a query string into an object; repeated keys become arrays.
- Convert 3 digits color to 6 digits color — Double each digit of a #rgb color.