Converting an RGB Color To Hex With JavaScript

UPDATE: 12/30 I had transposed the rgb colors. I corrected the function.

I’ve been distracted by a new jQuery plugin that I’m writing. The plugin has certain situations where it sets various background and foreground colors. You can have it set those styles explicitly or you can have it set a CSS class, and let the CSS stylesheet do the work.

color-wheelI’m writing some unit tests to test the former behavior and ran into an annoying quirk. When testing the color value in IE, I’ll get something like #e0e0e0, but when testing it in FireFox, I get rgb(224, 224, 224).

Here’s a function I wrote that normalizes colors to the hex format. Thus if the specified color string is already hex, it returns the string. If it’s in rgb format, it converts it to hex.

function colorToHex(color) {
    if (color.substr(0, 1) === '#') {
        return color;
    }
    var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);
    
    var red = parseInt(digits[2]);
    var green = parseInt(digits[3]);
    var blue = parseInt(digits[4]);
    
    var rgb = blue | (green << 8) | (red << 16);
    return digits[1] + '#' + rgb.toString(16);
};

Now, I can compare colors like so.

equals(colorToHex('rgb(120, 120, 240)'), '#7878f0');

I hope you find this useful. :)

What others have said

Requesting Gravatar... James Fuller Dec 29, 2009 9:25 PM
# re: Converting an RGB Color To Hex With JavaScript
I just wanted to point out, it looks like this code is switching the red and blue value, if you use the rgb values(120,120,240) your code returns #F07878 which is dominantly red, rather than dominantly blue, a fix to this is to remove the multiplier in front of the blue and multiply the red value by 65536. Just a quick analysis. Useful code otherwise.
Requesting Gravatar... Sergio Pereira Dec 29, 2009 9:52 PM
# re: Converting an RGB Color To Hex With JavaScript
If you want to normalize colors beyond the specific IE vs Firefox problem, you'll need to consider a few other color representations, like "rgb(10%, 30%, 30%)", "#aaa", "rgba(12, 34, 56, 20)".
Also, my JavaScript scars make me call out the missing radix parameter in parseInt.
If you download jquery-ui (full) you'll find a function called getRGB that normalizes colors into RGB arrays. Too bad the function is private.
Requesting Gravatar... Peter Obiefuna Dec 29, 2009 11:57 PM
# re: Converting an RGB Color To Hex With JavaScript
Kinda sounds like the same pain we know too well -- a pain deliberately inflicted on the world by MSFT when they chose to make IE non standard.

Let me guess: google chrome and safari handled the rgb thing just like Firefox didn't they?

Anyway, just to say, welcome to my world.
Requesting Gravatar... Artiom Chilaru Dec 30, 2009 12:07 AM
# re: Converting an RGB Color To Hex With JavaScript
I will have to agree with James Fuller. It seems to me as well that you have to swap the code to:
var dec = 65536 * red + 256 * green + blue
Requesting Gravatar... David Fowler Dec 30, 2009 1:57 AM
# re: Converting an RGB Color To Hex With JavaScript

var rgb = b | (g << 8) | (r << 16)


:)
Requesting Gravatar... "Cowboy" Ben Alman Dec 30, 2009 7:50 AM
# re: Converting an RGB Color To Hex With JavaScript

function hex( c ) {
var m = /rgba?\((\d+), (\d+), (\d+)/.exec( c );
return m
? '#' + ( m[1] << 16 | m[2] << 8 | m[3] ).toString(16)
: c;
};

hex( 'rgba(255, 136, 17, 0.5)' ); // '#ff8811'
hex( 'rgb(255, 136, 17)' ); // '#ff8811'
hex( '#ff8811' ); // '#ff8811'
hex( '#f81' ); // '#f81'

Requesting Gravatar... Justin Dec 30, 2009 7:58 AM
# re: Converting an RGB Color To Hex With JavaScript
hehe, I ran into this same thing a few months back. Came up with a similar solution but for the rgb (0, 0, 0) route I ended up getting the sub-string of what's in the '()' and splitting on the commas for the parts.

Nice solution, thanks :)
Requesting Gravatar... partha Dec 30, 2009 12:00 PM
# re: Converting an RGB Color To Hex With JavaScript
Can you explain this in more detail?

equals(colorToHex($('foo').css('color')), '#e0e0e0');

What's the $('foo')?

Can you give a detailed example of using the function?
Requesting Gravatar... John Dec 30, 2009 1:37 PM
# re: Converting an RGB Color To Hex With JavaScript
Partha,

http://letmebingthatforyou.com/?q=javascript%20dollar%20sign
Requesting Gravatar... Pita.O Dec 30, 2009 2:41 PM
# re: Converting an RGB Color To Hex With JavaScript
Hi Partha:
Please don't mind the sassiness.
$('foo') is a j@uery capture expression for an arbitrary html element foo. An specific example would be #('div').

So, colorToHex() function converts the css.color of that capture to Hexadesimal.

Finally, the equals() function checks if that hex value is equal to the string '#e0e0e0'
Requesting Gravatar... Pita.O Dec 30, 2009 2:45 PM
# re: Converting an RGB Color To Hex With JavaScript
Spelling corrections:
jQuery: not j@uery
A specific example would be $('div'): not "An ... #('div')
Requesting Gravatar... haacked Dec 30, 2009 3:51 PM
# re: Converting an RGB Color To Hex With JavaScript
Serves me right, testing against a color where the rgb values are all the same was stupid stupid stupid.

Thanks James for pointing out the error. Also, thanks to David fowler for pointing out the clever bit shifting approach.

I've corrected the function.
Requesting Gravatar... Adam Dec 30, 2009 7:07 PM
# re: Converting an RGB Color To Hex With JavaScript
Be careful with parseInt. It will return the wrong result for '01' so either use a + or parseInt("01",10)
Requesting Gravatar... Doeke Jan 01, 2010 11:52 AM
# re: Converting an RGB Color To Hex With JavaScript
I would also add some optional whitespace to the regex:

/(.*?)rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/
Requesting Gravatar... NC Jan 03, 2010 2:14 PM
# re: Converting an RGB Color To Hex With JavaScript
$('body').append('<div class="asdfghjkl"></div>');
$('.asdfghjkl').hide();
$('.asdfghjkl').css({ 'background': '#e0e0e0' });

equals($('.somecontainer').css("background-color"), $('.asdfghjkl').css("background-color"));
Requesting Gravatar... waqas Jan 03, 2010 10:57 PM
# re: Converting an RGB Color To Hex With JavaScript
great job,
keep it up
Requesting Gravatar... Loukas Jan 05, 2010 6:28 AM
# re: Converting an RGB Color To Hex With JavaScript
Great post!

I hope you enjoyed Elmo's Potty Time...
Requesting Gravatar... Divxindirizle Jan 09, 2010 9:56 AM
# re: Converting an RGB Color To Hex With JavaScript
Thank you for these useful informations. i will apply them right away
Requesting Gravatar... iPhoneKönig Jan 10, 2010 4:23 AM
# re: Converting an RGB Color To Hex With JavaScript
Thank you for these Great post!
Requesting Gravatar... Christopher X. Gerber Feb 11, 2010 11:59 AM
# re: Converting an RGB Color To Hex With JavaScript
"Cowboy" Ben's solution in original structure:

function RGBtoHex(rgb_color) {
if (rgb_color.substr(0, 1) === '#') {
return rgb_color;
}
var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(rgb_color);

var red = parseInt(digits[2]);
var green = parseInt(digits[3]);
var blue = parseInt(digits[4]);

var hex = (red << 16) | (green << 8) | blue;
return digits[1] + '#' + hex.toString(16);
}
Requesting Gravatar... Chris Hefley Apr 12, 2010 2:47 PM
# re: Converting an RGB Color To Hex With JavaScript
Maybe I'm missing something, but it appears that none of these solutions work with RGB values where the first value is 0. Hex numbers that should be rendered as #00ff00 come back as #ff00

Am I missing something? Please tell me I am, cause I'm tired of messing with this on my own. :)
Requesting Gravatar... Andrey Apr 12, 2010 3:58 PM
# re: Converting an RGB Color To Hex With JavaScript
Chris,
following line produces such a behaviour:
rgb = blue | (green << 8) | (red << 16)

For color #00ff00 red is zero, 0 << 16 gives 0, so
0 | (255 << 8) | 0 just equals to 0 | (255 << 8) = 65280 = FF00

For such a cases leading zeros needed.

Requesting Gravatar... Andy K May 18, 2010 4:54 AM
# re: Converting an RGB Color To Hex With JavaScript
I use this function to compare in javascript for toggling color in HTML but didn't work. Any suggest ??
...
...
<label style='color:#000000;' id='xx'>
...
...
<script>
function addtag(tag_)
{
if(document.getElementById('xx').style.color.toString(16) == rgb(0,0,0))
{
document.getElementById('xx').style.color = "#fff";
}
else
{
document.getElementById('xx').style.color = "#000";
}
</script>

Requesting Gravatar... Go2Store Jun 06, 2010 3:22 AM
# re: Converting an RGB Color To Hex With JavaScript
Thank you for these Great post!

it cool tip !!
Requesting Gravatar... Smithy Jun 24, 2010 2:02 PM
# re: Converting an RGB Color To Hex With JavaScript
Doeke is absolutely right: FF3.6 reports rgb colours with white space in them: rgb(34, 34, 34) - while IE8 has no spaces: rgb(34,34,34).

Thanks for the solutions!
Requesting Gravatar... myEnemy Jul 08, 2010 2:37 AM
# re: Converting an RGB Color To Hex With JavaScript
Hi, i've had the same problem comparing color terms like #00FFFF or #FF0FFF. My solution was to create leading zeros by brute force... Sorry for destroying your beautiful code :-)

function fillZero(myString) {
if (myString.length == 1) return "0" + myString;
else return myString;
}

function colorToHex(color) {
var digits = /(.*?)rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/.exec(color);
if (digits == null) return "";
var red = parseInt(digits[2]);
var green = parseInt(digits[3]);
var blue = parseInt(digits[4]);
var hexcode = fillZero(red.toString(16)) + fillZero(green.toString(16)) + fillZero(blue.toString(16));
return '#' + hexcode.toUpperCase();
}
Requesting Gravatar... Rod Byrnes Jul 26, 2010 12:30 AM
# re: Converting an RGB Color To Hex With JavaScript
The following works. It's a modification of Cowboy Ben's elegant solution but takes into account variable whitespace and colors with leading zeros.


function colorToHex(c) {
var m = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(c);
return m ? (1 << 24 | m[1] << 16 | m[2] << 8 | m[3]).toString(16).substr(1) : c;
}
Requesting Gravatar... Dave Cook Aug 04, 2010 5:56 PM
# re: Converting an RGB Color To Hex With JavaScript
One more tiny convenience fix - add the leading '#' needed for sending the output string back into jQuery, Google Earth etc. APIs:

function colorToHex(c) {
var m = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(c);
return m ? '#' + (1 << 24 | m[1] << 16 | m[2] << 8 | m[3]).toString(16).substr(1) : c;
}

What do you have to say?

(will show your gravatar)
Please add 7 and 6 and type the answer here: