When working with colors in web development, you may come across the need to convert HEX colors to RGB format. While HEX colors are commonly used in CSS, manipulating colors programmatically requires converting them to RGB or RGBA
In this blog, we'll explore how to convert HEX to RGB in JavaScript programmatically.
Understanding HEX and RGB Colors
Before diving into the conversion process, let's quickly understand what HEX and RGB colors represent:
HEX Color - HEX colors are represented as a six-digit combination of numbers and letters prefixed with a hash (#). For example, #FF0000 represents the color red.
RGB Color - RGB colors are represented by three values for red, green, and blue channels, ranging from 0 to 255. For example, RGB(255, 0, 0) also represents the color red.
Convert HEX to RGB in JavaScript
Converting HEX to RGB involves extracting the red, green, and blue values from the HEX color and converting them to their decimal equivalents.
Here's a code to achieve this conversion:
function hexToRgb(hex) {
// Remove the hash sign if present
hex = hex.replace('#', '');
// Convert HEX to RGB
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);
return `RGB(${r}, ${g}, ${b})`;
}
// Example usage
const hexColor = '#FF0000';
const rgbColor = hexToRgb(hexColor);
console.log(rgbColor); // Output: RGB(255, 0, 0)
Explanation
In the hexToRgb function:
- We remove the # sign from the HEX color string if present.
- We extract the red, green, and blue values from the HEX color and convert them to decimal using
parseInt(value, <base>)with abase of 16 (hexadecimal). - We return the RGB representation of the color using the extracted values.
Also checkout how to convert RGB to HEX in JavaScript
Tools to Convert HEX to RGB and RGB to HEX
Explore the quick tools for the conversion.

