Convert between hex, RGB, and HSL color formats
Quick Answer
`hexToRgb` parses a hex string into `{r, g, b}` using a regex and `parseInt(hex, 16)`. `rgbToHex` packs the three channels into a 24-bit integer and converts to hex with `toString(16)`.
1const hexToRgb = (hex) => {
2 const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
3 return result ? {
4 r: parseInt(result[1], 16),
5 g: parseInt(result[2], 16),
6 b: parseInt(result[3], 16)
7 } : null;
8};
9
10const rgbToHex = (r, g, b) => {
11 return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
12};Color format conversion is needed in design tools, data visualisation, and anywhere you need to apply dynamic colors programmatically. hexToRgb parses a hex string into {r, g, b} components using bit operations, and rgbToHex converts the three channel values back to a hex string using the same efficient bit-shifting approach.
First convert hex to RGB using `hexToRgb`, then apply the RGB-to-HSL formula: normalise channels to 0–1, compute lightness as `(max + min) / 2`, saturation, and hue from the dominant channel.
This free javascript code snippet for color converter is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement color converter quickly and correctly.
All snippets in the Snippetly library follow javascript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses javascript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.