Javascript – RGB to Hexadecimal Color Converter

While working on a side project today, I found the need for an RGB to hex color code converter in javascript. There are a number out there within a couple of easy Google searches, but I wasn’t happy with any of the ones that I found.

Every example I found other people had posted over the years involves using a string using 0-9, a-f and then using character matching and some math shifting to return a hex conversion. This irked me because javascript is perfectly capable of doing these conversions with native methods.

So what you will run into from time to time is that some browsers like Firefox and Safari return the css color value of an element as an RGB format, like RGB(204,0,0). Other browsers, namely Internet Explorer, return the hex code, like #cc0000.

What I wanted was a reusable method that will convert an RGB value to the equivalent hex number. It also had to be flexible enough to not be abused if I pass in a hex or non-RGB value. This helps it play nicely across different browsers. Its using native javascript “parseInt” and “toString” methods to do the converting. So enough chit-chat, here’s the damn code. =)

rgbhex = function(rgbval){
var s = rgbval.match(/rgbs*x28((?:25[0-5])|(?:2[0-4]d)|(?:[01]?d?d))s*,s*((?:25[0-5])|(?:2[0-4]d)|(?:[01]?d?d))s*,s*((?:25[0-5])|(?:2[0-4]d)|(?:[01]?d?d))s*x29/);

var d='',e;
if(s){ s=s.splice(1); }
	if(s && s.length==3){
		d='';
		for(i in s){
			e=parseInt(s[i],10).toString(16);
			e == "0" ? d+="00":d+=e;
		} return '#'+d;
	}else{ return rgbval; }
}

5 thoughts on “Javascript – RGB to Hexadecimal Color Converter

  1. hi! you’re script had a bug…

    function rgbToHex(rgbval){
    var s = rgbval.match(/rgbs*x28((?:25[0-5])|(?:2[0-4]d)|(?:[01]?d?d))s*,s*((?:25[0-5])|(?:2[0-4]d)|(?:[01]?d?d))s*,s*((?:25[0-5])|(?:2[0-4]d)|(?:[01]?d?d))s*x29/);
    if(s){
    s=s.splice(1);
    if(s && s.length==3){
    d=”;
    for(i in s){
    e=parseInt(s[i],10).toString(16);
    if(e.length == 1){
    e == “0” ? d+=”00″ : d+= (“0” + e);
    }else{
    d+=e;
    }
    } return ‘#’+d;
    }else{
    return rgbval;
    }
    }else{
    return rgbval;
    }
    }

  2. function rgb(r, g, b) {
    return “#” + (r + 256*g + 65536*b).toString(16);
    }

    var text = “rgb(20, 30, 40)”;

    var hex = eval(text);

    alert(hex);

    🙂

  3. Hi Uoon. Thanks for the feedback, but your function misses the point of what mine is trying to accomplish. Notice that I’m not passing in the individual r/g/b values. I am simply passing in a string that matches the pattern rgb(255,255,255). As I say in the post, IE returns the CSS value, while other browsers return an rgb value. So by using my method, I don’t have to worry about what the value is.

    My use-case is that I will only be using the rgb converter method when appropriate, i.e. when I am trying to guarantee a detected color value is going to be returned as a hex code. So by using this when I need it, I will guarantee that I *always* get the hex code value.

  4. Quite similar but avoids the somewhat complex .match line

    function rgbToHexColor(v) {
    v = v.split(‘(‘)
    if(!v[1]) return v
    v = v[1].replace(/ /g, ”).replace(/)/, ”)
    v = v.split(‘,’)
    for(i in v) {
    v[i] = Number(v[i]).toString(16)
    if(v[i].length==1) v[i] = ‘0’ + v[i]
    }
    return ‘#’+v.join(”)}

  5. Hi John, thanks for visiting the site and commenting.

    Your code sample has some errors (odd single/double quote marks) that I needed to correct, but this could easily be attributed to your text editor or the formatting my blog chose to use.

    I tested your code(fixed) versus my code in a loop that did the test loop 1000 times. In Firefox 3.0 and Safari 4 beta(the 2 browsers I tested in), my original code is generally faster than your sample. Additionally, the regex match does better validation about whether or not the string being passed in is an rgb value or not.

    In Firefox 3.0.10 on Mac, running the test 10 times:
    (My code :: Your code)
    22 :: 26
    21 :: 25
    20 :: 27
    21 :: 26
    19 :: 25
    20 :: 27
    19 :: 25
    21 :: 26
    19 :: 27
    22 :: 26

    Safari 4(beta)
    9 :: 7
    8 :: 7
    7 :: 6
    8 :: 7
    6 :: 7
    8 :: 7
    7 :: 7
    8 :: 7
    7 :: 8
    7 :: 8

    Safari has a very efficient js engine and for the most part, both of our versions are the same. But in the latest version of Firefox, my code is ~5 milliseconds faster. I would like to test this again in IE6/7/8 when I am able, but I suspect my version is faster there too. I would expect similar results as Safari for Chrome.

    Here’s the code I used for the test:
    //mine
    rgbhex = function(rgbval){

    var s = rgbval.match(/rgbs*x28((?:25[0-5])|(?:2[0-4]d)|(?:[01]?d?d))s*,s*((?:25[0-5])|(?:2[0-4]d)|(?:[01]?d?d))s*,s*((?:25[0-5])|(?:2[0-4]d)|(?:[01]?d?d))s*x29/);

    if(s){ s=s.splice(1); }
    if(s && s.length==3){
    var d=”;
    for(i in s){
    var e=parseInt(s[i],10).toString(16);
    e == “0” ? d+=”00″:d+=e;
    } return ‘#’+d;
    }else{ return rgbval; }

    }

    //his
    function rgbToHexColor(v) {
    v = v.split(‘(‘)

    if(!v[1]) return v

    v = v[1].replace(/ /g, ”).replace(/)/, ”)
    v = v.split(‘,’)

    for(i in v) {
    v[i] = Number(v[i]).toString(16)
    if(v[i].length==1) v[i] = ‘0’ + v[i]
    }

    return ‘#’+v.join(”)
    }

    window.onload = function(){

    var mystart = new Date().getTime();
    for(var i=0;i<1000;i++){

    var e = rgbhex(‘rgb(204,255,109)’);

    }
    var myend = new Date().getTime();

    var hisstart = new Date().getTime();
    for(var i=0;i<1000;i++){

    var e = rgbToHexColor(‘rgb(204,255,109)’);

    }
    var hisend = new Date().getTime();

    alert( (myend – mystart) + ‘ :: ‘ + (hisend – hisstart) );

    }

Leave a Reply

Your email address will not be published. Required fields are marked *