Convert RGB to Hex and Hex to RGB in Javascript

Convert RGB to Hex and Hex to RGB in Javascript

Hex Color: Red, Green and Blue. Hexadecimal numbers are used on web pages to set colors. Because a color can be made by mixing Red, Green and Blue. So it is called the “RGB Color System”

RGB (red, green, and blue) Color: refers to a system for representing the colors to be used on a computer display. Red, green, and blue can be combined in various proportions to obtain any color in the visible spectrum. Levels of R, G, and B can each range from 0 to 100 percent of full intensity.

Many times we need to convert RGB color code to Hex color code and Hex color code to RGB color code. We can easily perform this task using simple javascript function.

Convert RGB to Hex using Javascript


function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

alert( rgbToHex(0, 51, 255) ); // #0033ff

Convert Hex to RGB using Javascript


function hexToRgb(hex) {
var 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;
}

alert( hexToRgb("#0033ff").g ); // "51";