Note: both versions of rgbToHex expect integer values for r, g and b, so you'll need to do your own rounding if you have non-integer values.
The following will do to the RGB to hex conversion and add any required zero padding:
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
Converting the other way:
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";
Finally, an alternative version of rgbToHex(), as discussed in @casablanca's answer and suggested in the comments by @cwolves:
function rgbToHex(r, g, b) {
return "#" + (1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1);
}
alert(rgbToHex(0, 51, 255)); // #0033ff
Update 3 December 2012
Here's a version of hexToRgb() that also parses a shorthand hex triplet such as "#03F":
function hexToRgb(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var 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;
});
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";
alert(hexToRgb("#03f").g); // "51";
Answer from Tim Down on Stack OverflowNote: both versions of rgbToHex expect integer values for r, g and b, so you'll need to do your own rounding if you have non-integer values.
The following will do to the RGB to hex conversion and add any required zero padding:
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
Converting the other way:
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";
Finally, an alternative version of rgbToHex(), as discussed in @casablanca's answer and suggested in the comments by @cwolves:
function rgbToHex(r, g, b) {
return "#" + (1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1);
}
alert(rgbToHex(0, 51, 255)); // #0033ff
Update 3 December 2012
Here's a version of hexToRgb() that also parses a shorthand hex triplet such as "#03F":
function hexToRgb(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var 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;
});
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";
alert(hexToRgb("#03f").g); // "51";
An alternative version of hexToRgb:
function hexToRgb(hex) {
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return r + "," + g + "," + b;
}
Edit: 3/28/2017
Here is another approach that seems to be even faster
function hexToRgbNew(hex) {
var arrBuff = new ArrayBuffer(4);
var vw = new DataView(arrBuff);
vw.setUint32(0,parseInt(hex, 16),false);
var arrByte = new Uint8Array(arrBuff);
return arrByte[1] + "," + arrByte[2] + "," + arrByte[3];
}
Edit: 8/11/2017 The new approach above after more testing is not faster :(. Though it is a fun alternate way.
Changing hex codes to rgb values with JavaScript - Stack Overflow
[Share] RGB color parser in JavaScript
color2color.js - Simple JS to convert hex/RGB/RGBA/HSL/HSLA/HSV to hex/RGB/RGBA/HSL/HSLA/HSV string
How come JavaScript converts HEX colors to RGB?
» npm install hex-rgb
- Hex codes use base 16 (hexadecimal), RGB uses base 10 (decimal)
- Hex codes can be split into 3 bytes which describe red RR, green GG then blue BB, i.e. #RRGGBB
- The # for hex isn't always written, or sometimes it may use
0xor&hetc instead (you may need to consider this depending on your envionment)
Putting these together and using a RegExp to extract the interesting bits and parseInt to convert from the String representation of the base 16 numbers
function hex_to_RGB(hex) {
var m = hex.match(/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i);
return {
r: parseInt(m[1], 16),
g: parseInt(m[2], 16),
b: parseInt(m[3], 16)
};
}
// ex.
hex_to_RGB('#FF0110') // {r: 255, g: 1, b: 16}
When converting in the opposite direction you would use num.toString(16) and don't forget to pad the bytes with a '0' if they're smaller than (dec) 16
If you're starting with an Integer i which represents your hex colour, you can access the RGB values using bitwise operations, i.e.
var i = 0xFF0110, // 16711952
rgb = {
r: (i >> 16) & 0xFF, // or `(i & 0xFF0000) >> 16`
g: (i >> 8) & 0xFF, // or `(i & 0x00FF00) >> 8`
b: i & 0xFF // or ` i & 0x0000FF `
}; // {r: 255, g: 1, b: 16}, same as before
A legal hex color can be 3 or 6 characters after the '#', and rgb components
can be either percentages or numbers between 0 and 255.
function hexToRgb(c){
if(/^#([a-f0-9]{3}){1,2}$/.test(c)){
if(c.length== 4){
c= '#'+[c[1], c[1], c[2], c[2], c[3], c[3]].join('');
}
c= '0x'+c.substring(1);
return 'rgb('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+')';
}
return '';
}
function rgbToHex(rgb){
var c= rgb.match(/\d+(\.\d+)?%?/g);
if(c){
c= c.slice(0, 3).map(function(next){
var itm= next;
if(itm.indexOf('%')!= -1){
itm= Math.round(parseFloat(itm)*2.55);
}
if(itm<0) itm= 0;
if(itm>255) itm= 255;
itm= Math.round(itm).toString(16);
if(itm.length== 1) itm= '0'+itm;
return itm;
});
return '#'+c.join('').toLowerCase();
}
return '';
}