To convert hex to RGB in JavaScript, expand shorthand CSS hex to two digits per channel, then parse each pair as base 16 to obtain channel bytes from 0 to 255.
The exact parsing rules matter because CSS supports several hexadecimal lengths, and only some of them contain transparency. A reliable JavaScript function should validate the complete token before splitting it, preserve the correct channel order, and provide separate values for code that needs integers rather than a CSS string.

The channel math JavaScript needs
In the six-digit #RRGGBB notation, the first pair represents red, the second green, and the third blue. The equivalent JavaScript operation is parseInt(channelPair, 16), where channelPair is a two-character hexadecimal string. The result is an integer byte from 0 through 255.
Three-digit and four-digit values require expansion before that operation. Each shorthand digit is duplicated, so one digit becomes two hexadecimal digits and then forms one complete channel. Eight-digit CSS colors also contain a final alpha pair. Its opacity is the alpha byte divided by 255.
| CSS format | Structure | Alpha behavior |
|---|---|---|
| #RGB | Three shorthand digits expanded to six digits | No alpha is specified; the preview is fully opaque |
| #RGBA | Four shorthand digits expanded to eight digits | Contains a final alpha byte |
| #RRGGBB | Two digits for each RGB channel | No alpha is specified; the preview is fully opaque |
| #RRGGBBAA | Two digits for each RGB channel and alpha | Alpha comes last, after blue |
These formats follow MDN's CSS hex-color reference and CSS Color Level 4 hexadecimal notation. Other color syntaxes are separate inputs rather than accepted variants of this conversion.
Build a reusable JavaScript converter
The following function validates the entire token, expands shorthand notation, converts every pair to an integer, and returns both CSS and component-level output.
JavaScript: function cssHexToRgb(input) { if (typeof input !== "string") throw new Error("Expected a CSS hex color."); const hex = input.trim(); const match = /^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(hex); if (!match) throw new Error("Use #RGB, #RGBA, #RRGGBB, or #RRGGBBAA."); const digits = match[1]; const expanded = digits.length <= 4 ? [...digits].map((digit) => digit + digit).join("") : digits; const [r, g, b, a] = expanded.match(/../g).map((part) => parseInt(part, 16)); const alphaByte = a; const alpha = alphaByte === undefined ? undefined : Number((alphaByte / 255).toFixed(3)); return { hex: `#${expanded.toLowerCase()}`, r, g, b, alphaByte, alpha, css: alphaByte === undefined ? `rgb(${r}, ${g}, ${b})` : `rgba(${r}, ${g}, ${b}, ${alpha})` }; }
The regular expression checks the complete value instead of allowing parseInt to accept a valid-looking prefix. Trimming removes whitespace around the token but does not permit spaces inside it. Uppercase and lowercase letters are equivalent. The returned hex value is normalized to lowercase, while alphaByte retains the exact integer behind the readable CSS opacity.
Use the converter in a JavaScript project
- Store cssHexToRgb in the module or script that owns your color handling.
- Pass the complete CSS token, including its leading #, to the function. Use a call such as const result = cssHexToRgb(userInput); when the value comes from a form or configuration.
- Read result.r, result.g, and result.b when an API, canvas operation, design token, or test fixture needs separate integer channels.
- Use result.css for a style declaration, such as assigning it to element.style.color. The function returns rgb() when alpha is absent and rgba() when it is present.
- Wrap the call in error handling when users can enter the value. A rejected token should produce an input error rather than an object containing partially parsed channels.
Keeping validation, channel parsing, and formatting in one function prevents different parts of an application from disagreeing about shorthand expansion or alpha order. It also gives callers a clear choice between a ready-to-use CSS string and separate numeric values.
Check a token with the browser converter
When you need to inspect a color without writing code, the HEX to RGB Converter parses CSS hexadecimal colors and shows the normalized value, channel bytes, CSS representation, alpha information, and live preview.
- Paste a CSS hexadecimal color beginning with #. The accepted forms are #RGB, #RGBA, #RRGGBB, and #RRGGBBAA.
- Read the expanded lowercase hexadecimal value together with the generated rgb() or rgba() string.
- Review the individual red, green, blue, and alpha values when the result will be used as numeric data.
- Check the live preview to catch an obvious channel-order mistake.
- For a translucent color, retain the exact alpha byte when a rounded decimal would not preserve the original value precisely.
Conversion happens immediately in the current browser. Parsing, validation, formatting, and preview rendering are local, and the color string is not uploaded to Lizely. Empty or invalid input replaces the previous conversion with a clear error instead of leaving a stale successful result on screen.
Keep alpha in the right order
CSS places transparency last in #RRGGBBAA. Red comes first, green second, blue third, and alpha fourth. Some eight-digit conventions used outside CSS put opacity first, but a CSS parser should not silently reinterpret or reorder those values.
For one complete example, #0f08 expands to #00ff0088. Its channel bytes are red 0, green 255, blue 0, and alpha 136. The CSS opacity calculation is 136 / 255 = 0.533333..., which is displayed to three decimal places as 0.533. The exact byte 136 and normalized hex value remain available when that small rounding difference matters.
Three- and six-digit values do not specify alpha and are treated as fully opaque for the preview. For a translucent color, keep the normalized eight-digit hex or the exact alpha byte when round-trip precision is important; a short decimal in rgba() is intended primarily for readability.
Match each output to its consumer
Converting the notation does not make every output equally suitable for every task. Choose the representation expected by the system that will consume the color.
| Output | Appropriate use | Important detail |
|---|---|---|
| RGB channel bytes | Canvas operations, APIs, image editors, test fixtures, and design tokens | Separate integer values from 0 through 255 |
| Exact alpha byte | Systems that require precise transparency | Present only when the source includes alpha |
| CSS color string | Stylesheets and inline style properties | Uses rgb() or rgba() as appropriate |
| Normalized hex | Design tokens, fixtures, and exact color round trips | Expanded to lowercase and retains the exact alpha byte when present |
Use integer channels when the destination API asks for red, green, and blue separately. Use the CSS output when a browser or stylesheet accepts functional color notation. Keep normalized hex for exact sharing, especially when a translucent value's alpha cannot be represented fully by a short decimal.
Reject malformed tokens deliberately
A strict parser should make invalid input visible rather than guessing what the author intended. The accepted CSS boundary excludes several values that a design application might tolerate.
- A missing hash is invalid, so RGB and 123456 are not accepted as CSS hex tokens.
- Only three, four, six, or eight hexadecimal digits are allowed. Five- and seven-digit values are not converted.
- Doubled hashes, embedded spaces, and characters outside 0–9 and A–F are rejected.
- Uppercase and lowercase letters mean the same thing, while whitespace around the complete value may be trimmed.
The converter does not parse named colors such as rebeccapurple, or inputs written as hsl(), lab(), lch(), color(), system colors, CSS variables, gradients, or comma-separated palettes. It also does not treat #AARRGGBB as CSS alpha-first notation or reorder its components.
Understand what the preview does not prove
The live preview is useful for spotting an obvious mistake, but it is not a color-management reference. Screens, browser profiles, brightness settings, ambient light, and wide-gamut workflows can make the same numeric sRGB value look different. CSS hexadecimal colors represent sRGB channels; they are not Pantone references, CMYK ink recipes, or physical measurements.
The conversion also does not measure contrast, choose an accessible foreground, sample pixels from an image, or convert between color spaces. For a text-and-background pair, use the Color Contrast Checker rather than judging readability from the color preview. A dependable workflow verifies the expected digit count, confirms CSS's alpha-last order, and compares the displayed channel values with the system that will consume them.
Related reading: RGB to CMYK for PDF: A Practical Per-Color Workflow.
Related reading: Does ABC Shorthand Work When I Convert RGB to HEX?.