To convert hex to RGB in JavaScript, validate the CSS hex token, expand any shorthand, split it into byte pairs, and parse each pair in base 16.

HEX and RGB are two representations of the same sRGB channel values. A six-digit CSS color such as #RRGGBB stores red, green, and blue in that order, while #RRGGBBAA adds an alpha byte at the end. A three- or four-digit version uses shorthand, so the parser must expand it before reading individual channels.

For a quick browser-based conversion, the HEX to RGB Converter accepts CSS hexadecimal notation and displays the normalized HEX, CSS rgb() or rgba() value, channel bytes, alpha information, and a live preview. The following JavaScript implementation applies the same channel-ordering rules without relying on a visual estimate.

convert hex to rgb javascript
Convert Hex to RGB JavaScript: Strict CSS Parsing

JavaScript conversion for CSS hex tokens

This function accepts a string containing #RGB, #RGBA, #RRGGBB, or #RRGGBBAA. It rejects malformed values, expands shorthand, and returns both integer channels and a CSS-ready string.

Reusable function: function hexToRgb(input) { const hex = input.trim(); if (!/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(hex)) { throw new Error("Expected #RGB, #RGBA, #RRGGBB, or #RRGGBBAA"); } const digits = hex.slice(1); const expanded = digits.length <= 4 ? digits.split("").map(d => d + d).join("") : digits; const bytes = expanded.match(/.{2}/g).map(pair => parseInt(pair, 16)); const [r, g, b, alphaByte] = bytes; const alpha = alphaByte === undefined ? 1 : alphaByte / 255; return { r, g, b, alphaByte, alpha, normalized: `#${expanded.toLowerCase()}`, css: alphaByte === undefined ? `rgb(${r}, ${g}, ${b})` : `rgba(${r}, ${g}, ${b}, ${alpha})` }; }

Pass a string to hexToRgb and read the returned fields according to the destination. The r, g, and b properties are integer bytes from 0 through 255. The alphaByte property is always present; when the source does not contain alpha, its value is undefined, while alpha is 1. The normalized property contains the expanded lowercase HEX value, while css contains the corresponding rgb() or rgba() declaration value.

  • For a stylesheet: use the returned css value.
  • For canvas, an API, or another channel-based API: use the integer r, g, and b properties.
  • For an exact translucent round trip: retain normalized and alphaByte.

Convert a CSS hex color in your browser

  1. Paste the CSS hexadecimal color. Include the leading # and use a three-, four-, six-, or eight-digit value.
  2. Read the conversion results. Review the normalized hexadecimal value, CSS rgb() or rgba() string, and individual channel bytes.
  3. Check the live preview. For a translucent color, retain the alpha byte and normalized HEX when exact round-trip precision matters.

The conversion happens immediately in the current browser. Parsing, formatting, validation, and preview rendering stay local, so the color string is not uploaded to Lizely. Three- and six-digit inputs are treated as fully opaque for the preview because they do not contain an alpha component.

CSS hex forms and channel order

CSS input Expanded form Channel order CSS output
#RGB #RRGGBB Red, green, blue rgb()
#RGBA #RRGGBBAA Red, green, blue, alpha rgba()
#RRGGBB #RRGGBB Red, green, blue rgb()
#RRGGBBAA #RRGGBBAA Red, green, blue, alpha rgba()

The accepted forms follow MDN’s CSS hex-color reference. Uppercase and lowercase letters have the same meaning. In shorthand, each digit represents one hexadecimal nibble, so duplicating each digit converts it into a full byte before parsing.

For one worked example, #123 expands to #112233. Parsing the pairs 11, 22, and 33 with parseInt(pair, 16) produces R = 17, G = 34, and B = 51.

Alpha always comes last in CSS. The CSS Color Level 4 hexadecimal notation defines #RRGGBBAA, not the opacity-first arrangement used by some non-CSS conventions. A converter must not reinterpret #AARRGGBB or reorder it according to the color that appears on screen.

Choose the output your code needs

Different consumers need different representations of the same color. Choosing the right output prevents an otherwise correct conversion from losing precision or failing to fit the destination format.

  • Use rgb() or rgba() for CSS styles. These values can be assigned directly to properties that accept CSS color syntax.
  • Use separate channel bytes for code that expects integers. Canvas operations, image editors, API payloads, test fixtures, and design tokens often consume red, green, and blue as numbers from 0 through 255.
  • Use normalized HEX for exact round trips. This is particularly important for translucent colors because a short decimal alpha can lose a small amount of precision.

The alpha byte is an integer from 0 through 255, and its opacity is calculated by dividing that byte by 255. The converter presents a readable decimal with up to three decimal places, but also keeps the exact alpha byte and normalized hexadecimal value. The JavaScript function above returns the unrounded ratio in its alpha property, making the alphaByte field the safest source for precision-sensitive work.

Reject invalid or ambiguous values

A strict parser should expose an invalid CSS token instead of silently guessing what the author intended. The validation in the JavaScript function enforces the same accepted boundaries as the converter.

  • Require the leading hash. A value without # is rejected because it is not a complete CSS hexadecimal color.
  • Allow only exact lengths. Three, four, six, and eight digits are accepted; five- and seven-digit strings are not.
  • Reject embedded whitespace and invalid characters. Only hexadecimal digits from 0 through 9 and letters from A through F are accepted inside the value.
  • Do not reorder channels. Red comes first, green second, blue third, and alpha last when present.

Ordinary whitespace around the complete input is trimmed, so a copied value with surrounding spaces can still be processed. Embedded spaces remain invalid. The converter does not parse named colors, hsl(), lab(), lch(), color(), system colors, CSS variables, gradients, or comma-separated palettes.

An empty or invalid value also replaces the previous conversion with a clear error in the browser tool. That prevents a stale successful result from appearing to belong to the value currently being edited.

Understand what the preview confirms

The live preview renders the generated CSS color, which makes it useful for spotting an obvious channel-order mistake. It is not a color-management reference. Screen quality, browser profiles, display brightness, ambient light, and wide-gamut workflows can make the same numeric sRGB value look different on different devices.

Hexadecimal CSS colors represent sRGB channel values, not Pantone matches, CMYK ink recipes, or physical color measurements. The converter does not convert between color spaces, calculate contrast, select an accessible foreground, sample pixels from an image, or determine how two colors will appear in print. A preview can confirm that the browser accepts the generated value, but production color decisions still require the appropriate downstream workflow.

A dependable hand-off checklist

Before using the converted values, copy the complete CSS token including its hash and confirm that it contains the expected number of digits. Compare the displayed red, green, and blue values with the system that will consume them. When transparency is involved, confirm that the source follows CSS’s alpha-last ordering.

Use the JavaScript function for values that enter an application dynamically, such as user-supplied theme colors or data-driven design tokens. Use the browser converter for a static color that needs to be checked and copied into CSS, an API payload, a canvas routine, or a test fixture. Retain the normalized HEX when a translucent value must survive the hand-off without the small rounding loss associated with a short decimal alpha.

Related reading: How to Compare HTML and CSS Color Names Chart Methods.

Related reading: Free RGB to CMYK Converter: Convert Numeric Color Values.