How to Convert HEX Color to RGB in JavaScript (3 Ways)

Published April 2025 · 5 min read

Three ways to convert HEX to RGB in JavaScript, from simplest to most robust.

Method 1: One-Liner

const hexToRgb = hex => hex.match(/\w\w/g).map(x => parseInt(x, 16));
hexToRgb("#2563eb"); // [37, 99, 235]

Method 2: Named Function

function hexToRgb(hex) {
  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);
  return { r, g, b };
}
hexToRgb("#2563eb"); // {r: 37, g: 99, b: 235}

Method 3: With Shorthand Support (#fff)

function hexToRgb(hex) {
  hex = hex.replace(/^#/, '');
  if (hex.length === 3) {
    hex = hex.split('').map(c => c + c).join('');
  }
  const num = parseInt(hex, 16);
  return [(num >> 16) & 255, (num >> 8) & 255, num & 255];
}
hexToRgb("#fff"); // [255, 255, 255]

RGB to HEX (Reverse)

const rgbToHex = (r, g, b) => '#' + [r, g, b].map(x => x.toString(16).padStart(2, '0')).join('');
rgbToHex(37, 99, 235); // "#2563eb"

Try It Visually

Use our Color Picker to convert between HEX, RGB, and HSL interactively.

Related