Color Conversion in JavaScript
Convert HEX, RGB, and HSL colors programmatically in JavaScript — without libraries.
Published:
Tags: color conversion JavaScript, hex to rgb JavaScript, JavaScript color parser
Color Conversion in JavaScript JavaScript's native functions convert colors between hex, RGB, and HSL without libraries. The math is straightforward—parse hex strings with parseInt, compute HSL from RGB using max/min normalization, and format CSS values. These techniques handle edge cases like 3-digit shorthand hex and normalized ranges reliably. For a visual converter, see Color Converter: HEX, RGB, HSL. For the EyeDropper API, see EyeDropper API in JavaScript. For the full color tools overview, see the Color Tools for Designers and Developers guide. --- What is Color Format Conversion? | From Format | To Format | Use | Example | |-------------|-----------|-----|---------| | Hex | RGB | Web display | #FF5733 → rgb(255, 87, 51) | | RGB | Hex | Shorthand | rgb(255, 87, 51) → #FF5733 | |…
Frequently Asked Questions
How do I convert hex to RGB in JavaScript?
Parse the hex string into three two-character substrings and convert each with `parseInt(str, 16)`. For `#1a73e8`: R = parseInt('1a', 16) = 26, G = parseInt('73', 16) = 115, B = parseInt('e8', 16) = 232. Handle the 3-digit shorthand by expanding each digit: '#1af' becomes '#11aaff'.
How do I convert RGB to HSL in JavaScript?
Normalize R, G, B to 0–1, compute max and min. Lightness is (max + min) / 2. Saturation is (max - min) / (1 - |2L - 1|) when L is not 0 or 1. Hue is determined by which channel is the max — the formula calculates an angle from the ratio of the remaining two channels. Full implementation in this article.
How do I parse a CSS color string in JavaScript?
For hex strings, use a regex. For `rgb()` and `hsl()` strings, extract numeric values with a regex or split by comma. For named colors, create a temporary element, set its style to the color, then read back `getComputedStyle().color` — the browser normalizes it to `rgb()` form. This technique handles all 140 named colors.
How do I generate a random color in JavaScript?
Use `Math.random()` for each RGB channel: `const r = Math.floor(Math.random() * 256)`. For a random HSL color with controlled saturation and lightness, fix S and L and randomize only H: `hsl(${Math.floor(Math.random() * 360)}, 70%, 50%)`. This produces vivid, balanced colors instead of muddy random RGB values.
What is the best JavaScript color library?
For most color manipulation tasks, native JavaScript with manual conversion functions is sufficient and has zero bundle cost. If you need extensive color space support (Lab, oklch, color-mix), chroma-js is the most widely used library. For design systems that need WCAG contrast calculation built-in, polychrome or culori are well-maintained alternatives.
All articles · theproductguy.in