How to Convert RGB to Hex and Vice Versa

In this tutorial, we suggest several methods of converting RGB to Hex and vice versa. Let’s convert RGB value to Hex value. There are two versions of rbgtoHex which expect integer values for r, g and b.

This following code does RGB to Hex conversion and add any required zero padding:

Javascript convert RGB to Hex
function componentToHex(c) { let hex = c.toString(16); return hex.length == 1 ? "0" + hex : hex; } function rgbToHex(r, g, b) { return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b); } console.log(rgbToHex(28, 135, 201)); // #1c89c9

Here is the alternative way to the above method:

Javascript convert RGB to Hex
function rgbToHex(r, g, b) { return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); } console.log(rgbToHex(28, 135, 201)); // #1c87c9

Now let’s convert hex into RGB:

Javascript convert Hex to RGB
function hexToRgb(hex) { let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } console.log(hexToRgb("#1c87c9").b); //201

There is another version of hexToRgb() that also parses a shorthand hex triplet:

Javascript convert hexToRGB method
function hexToRgb(hex) { let shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, function (m, r, g, b) { return r + r + g + g + b + b; }); let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } console.log(hexToRgb("#0044ff").g); console.log(hexToRgb("#04f").g);

HEX and RGB

Hexadecimal (also known as base 16, or hex) is a positional numeral system with a radix of 16. It uses 16 distinct symbols 0–9 for representing values zero to nine, and A–F for representing values ten to fifteen.

The RGB colour is an additive colour model in which red, green and blue are added together to reproduce an array of colours. Each parameter specifies the intensity of the colour and can be an integer between 0 and 255 or a percentage value between 0% and 100%.