JavaScript

Hex ↔ RGB Conversion

by @admin
10h ago
Apr 28, 2026
Public
Converts between hex colour strings (#rrggbb / #rgb) and RGB component objects. hexToRgb parses both shorthand and full hex formats. rgbToHex converts R, G, B integers (0–255) back to a hex string. Handy for colour manipulation, generating CSS variables, and passing colour data between libraries.
JavaScript
function hexToRgb(hex) {
  const full = hex.replace(/^#([a-f\d])([a-f\d])([a-f\d])$/i,
    (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`);
  const result = /^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(full);
  return result
    ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) }
    : null;
}

function rgbToHex(r, g, b) {
  return '#' + [r, g, b].map((v) => v.toString(16).padStart(2, '0')).join('');
}

// Usage
console.log(hexToRgb('#ff6600'));    // { r: 255, g: 102, b: 0 }
console.log(hexToRgb('#f60'));       // { r: 255, g: 102, b: 0 }
console.log(rgbToHex(255, 102, 0)); // #ff6600
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.