Convert RGB to HEX and HEX to RGB using Javascript (Online Demo)
Recently I was developing a react project where I required to convert RGB to HEX color values and HEX to RGB color values so I wrote Javascript functions for it.
Article is divided into following sections
In this article I will explain how to create your own RGB to HEX and HEX to RGB functions. Explanation might be useful for beginners or users who would want to tweak these functions to fit their needs. If you are looking for just the code, please skip to the Code part.
Explanation
Before we start coding, let us understand what we are trying to achieve. RGB and HEX are 2 color representational forms. I generally use them in CSS to style webpages, but they might be used at other places as well like photoshop, etc. A HEX representation of color white would be #ffffff while RGB representation would be rgb(255,255,255). A HEX representation of color black would be #000000 while RGB representation would be rgb(0,0,0).
So, we understand that HEX color values can range from #000000 to #ffffff. Where color code is 6 character long (excluding # sign) and each character is a hexadecimal number between 0-f (decimal values: 0-15)
Each pair in the 6 characters represent one of the three color components Red, Green and Blue. So a hexadecimal code for color red which is #FF0000 indicates Red: FF (decimal: 255), Green: 00 (decimal: 0), Blue: 00 (decimal: 0)
From above example, we can understand that RGB representation is nothing but decimal representation of HEX color code. For e.g. RGB color code for color red is rgb(255, 0, 0) and HEX representation is #ff0000
We are now clear on what we want to achieve. For RGB to HEX conversions, we will accept 3 parameters i.e. Red, Green, and Blue. Each of these would be the decimal values ranging between 0-255. We will convert each of them to hexadecimal value and provide the output. Similarly, for HEX to RGB conversion, we will accept HEX color code, extract 3 pairs of hexadecimal values from the string and convert them to decimal. We will return an object (or array, if you prefer) with these 3 values indicating red, green and blue color codes.
So, let us begin with rgb2hex function accepting 3 parameters.
function rgb2hex(r, g, b) {
}
Next, we convert each of these 3 values to respective hexadecimal values. But we also need to remember that values 0-15 will be converted to single character 0-f, hence if length of converted value is less than 2, we prefix (left-pad) it with 0. So 0 will be converted to hex 00, while 15 will be converted to 0f (instead of only f).
Note: I have also added “parseInt()” function, just in case you are taking input directly from the user. This takes care of converting string (user input) to integer. You need not use this if you are validating inputs prior to passing and are sure that they are integers. To handle parseInt() exceptions, we surround the code with try-catch block. We will return false in case of error.
function rgb2hex(r, g, b) {
try {
var rHex = parseInt(r).toString(16).padStart(2, '0');
var gHex = parseInt(g).toString(16).padStart(2, '0');
var bHex = parseInt(b).toString(16).padStart(2, '0');
} catch (e) {
return false;
}
}
Finally, check to validate that value is not overflowing. Eg. if 256 was passed as a value, converted hex value would be 100. To handle this, I am checking length of the converted value. Maximum value of converted hexadecimal would be ff, anything above that would result in more than 2 characters. Thus, if length of any of converted values is greater than 2, we return false.
function rgb2hex(r, g, b) {
try {
var rHex = parseInt(r).toString(16).padStart(2, '0');
var gHex = parseInt(g).toString(16).padStart(2, '0');
var bHex = parseInt(b).toString(16).padStart(2, '0');
} catch (e) {
return false;
}
if (rHex.length > 2 || gHex.length > 2 || bHex.length > 2) return false;
return '#' + rHex + gHex + bHex;
}
That sums up for RGB to HEX conversion.
Now, we create function for hex color code to RGB conversion. We will receive as input hex value, e.g. #ffffff and we will be returning an object with 3 components i.e. red, green and blue as output.
Let us understand how we go about this.
First we split the provided hex color code into 3 parts as follows:
- Ignore “#” sign at the start
- First 2 characters are red hexadecimal value
- Next 2 characters are green hexadecimal value
- Last 2 characters are blue hexadecimal value
We could now use substring method to extract this information. But I prefer to use RegExp.prototype.exec() approach instead. RegExp.prototype.exec() function matches a regular expression with a string. If it does not find a match, it returns null. This way we can immediately return false if no matches are found.
Building the regex might be tricky if you are not a comfortable with it. I will briefly explain how we got the regex in below code. We are trying to match an a string which
- is 6 or 7 characters long
- first character is # (which is optional, hence we use a “?” after #)
- next 6 characters are composed of 3 pairs of 2 characters which follow below pattern:
– exactly 2 characters (Regex: {2}), made up of either alphabets a-f (Regex: [a-f]) or digits (Regex: [/d]) => Combined regex ([a-f/d]{2})
We include above pattern in round brackets so that it gets extracted in result array. Repeat this same code 2 more times to identify rest of the 2 pairs for green and blue respectively.
function hex2rgb(hex) {
var validHEXInput = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
if (!validHEXInput) {
return false;
}
}
So we have handled wrong input scenario above. Hence we are certain that input provided is a valid hexadecimal color code. But how do we get 3 pairs of color code? Remember our function RegExp.prototype.exec() used earlier? That’s right, this function extracts the matches (enclosed in round brackets as elements of array returned). We need to skip the first element array[0] as it will be a total string matched, which would same as input string itself and we don’t need that. So, we pick next three values of returned array and map to respective RGB component.
- array[1] => red,
- array[2] => green,
- array[3] => blue.
Finally, all we need to do now is convert these hexadecimal values to integers and return an object with these 3 integer values.
function hex2rgb(hex) {
var validHEXInput = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
if (!validHEXInput) {
return false;
}
var output = {
r: parseInt(validHEXInput[1], 16),
g: parseInt(validHEXInput[2], 16),
b: parseInt(validHEXInput[3], 16),
};
return output;
}
That’s it, we have completed HEX to RGB conversion as well.
Code
Here are ready to use Javascript functions to convert HEX color value to RGB color value and RGB color value to HEX color value.
function rgb2hex(r, g, b) {
try {
var rHex = parseInt(r).toString(16).padStart(2, '0');
var gHex = parseInt(g).toString(16).padStart(2, '0');
var bHex = parseInt(b).toString(16).padStart(2, '0');
} catch (e) {
return false;
}
if (rHex.length > 2 || gHex.length > 2 || bHex.length > 2) return false;
return '#' + rHex + gHex + bHex;
}
RGB to HEX function accepts RGB code as input in form of 3 parameters and returns output as HEX code or false in case of errors.
function hex2rgb(hex) {
var validHEXInput = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
if (!validHEXInput) {
return false;
}
var output = {
r: parseInt(validHEXInput[1], 16),
g: parseInt(validHEXInput[2], 16),
b: parseInt(validHEXInput[3], 16),
};
return output;
}
HEX to RGB function accepts HEX code as input (starting with # sign) and returns an object which holds 3 values for red, green and blue color components. Function returns false in case of errors.
Covert Hex to RGB & RGB to HEX Online Demo
HTML Code
Following is a code you can save as .html file on your system and run it locally.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>HEX to RGB and RGB to HEX</title>
<script type="text/javascript">
function hex2rgb(hex) {
var validHEXInput = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
if (!validHEXInput) {
return false;
}
var output = {
r: parseInt(validHEXInput[1], 16),
g: parseInt(validHEXInput[2], 16),
b: parseInt(validHEXInput[3], 16),
};
return output;
}
function rgb2hex(r, g, b) {
try {
var rHex = parseInt(r).toString(16).padStart(2, '0');
var gHex = parseInt(g).toString(16).padStart(2, '0');
var bHex = parseInt(b).toString(16).padStart(2, '0');
} catch (e) {
return false;
}
if (rHex.length > 2 || gHex.length > 2 || bHex.length > 2) return false;
return '#' + rHex + gHex + bHex;
}
function convertRGBtoHEX() {
var input = document.getElementById('rgb-input').value.split(',');
if (input.length === 3) {
var output = rgb2hex(input[0], input[1], input[2]);
if (output === false) {
return alert('Enter input in format d,d,d where d is a number between 0-255');
}
return (document.getElementById('hex-output').value = rgb2hex(input[0], input[1], input[2]));
}
return alert('Enter input in format d,d,d where d is a number between 0-255');
}
function convertHEXtoRGB() {
var input = document.getElementById('hex-input').value;
var output = hex2rgb(input);
if (output === false) {
return alert('Enter valid hex code for input. E.g. #f0db4f');
}
document.getElementById('rgb-output').value = 'rgb(' + output.r + ', ' + output.g + ', ' + output.b + ')';
}
</script>
</head>
<body>
<fieldset>
<legend>RGB to HEX:</legend>
<label for="rgb-input">RGB Input: </label>
<input type="text" id="rgb-input" placeholder="RGB input: Ex. 123,234,20" value="123,234,20" /><br /><br />
<label for="hex-output">HEX Output: </label>
<input type="text" id="hex-output" disabled placeholder="HEX output" /><br /><br />
<input type="button" value="Convert" onclick="convertRGBtoHEX()" />
</fieldset><br /><br />
<fieldset>
<legend>HEX to RGB:</legend>
<label for="hex-input">HEX Input: </label>
<input type="text" id="hex-input" placeholder="HEX input: Ex. #f0db4f" value="#f0db4f" /><br /><br />
<label for="rgb-output">RGB Output: </label>
<input type="text" id="rgb-output" disabled placeholder="HEX output" /><br /><br />
<input type="button" value="Convert" onclick="convertHEXtoRGB()" />
</fieldset>
</body>
</html>