Articles :: JavaScript :: hex2rgb / rgb2hex

written by Toby Miller on September 1, 2005
September 1, 2005

I'm sure you've come across the need to interchange hex and rgb values at one time or another; for color conversions, cross-browser hacks or whatever the reason. Here are the two functions that I use to get the job done.

   1:/**
   2: * convert hexadecimal to rgb
   3: *
   4: * @param string hex color
   5: * @return array array(r, g, b), null on failure
   6: */
   7:function hex2rgb(hex)
   8:{
   9:    var regexp = new RegExp('^#?([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$');
  10:    var match = hex.toLowerCase().match(regexp);
  11:
  12:    if (match)
  13:    {
  14:        var rgb = new Array(parseInt(match[1], 16), parseInt(match[2], 16), parseInt(match[3], 16));
  15:        return(rgb);
  16:    }
  17:    else
  18:    {
  19:        return(null);
  20:    }
  21:}
  22:
  23:/**
  24: * convert rgb to hexadecimal
  25: *
  26: * @param integer red
  27: * @param integer green
  28: * @param integer blue
  29: * @return string hex color
  30: */
  31:function rgb2hex(red, green, blue)
  32:{
  33:    var hex = new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');
  34:    var rgb = new Array();
  35:    var k = 0;
  36:
  37:    for (var i = 0; i < 16; i++) for (var j = 0; j < 16; j++) { rgb[k] = hex[i] + hex[j]; k++ }
  38:
  39:    return('#' + rgb[red] + rgb[green] + rgb[blue]);
  40:}
  41:

These functions are also available in my Common JavaScript Library.

permalink                                                                                                                                                                          
   Natural Living (5)
      Heating & Cooling (1)
      Herbal Remedies (1)
   Personal (0)
      Family (1)
      Humor (11)
      Miscellaneous (1)
      Politics (5)
   Technology (2)
      System Administration (4)
            Linux (1)
            Solaris (0)
      Web Development (2)
            CSS (3)
            Design (1)
            Flash (1)
            JavaScript (11)
            PHP (1)
                        CakePHP (1)
            Web Browsers (2)
                        Firefox (1)
                        Internet Exploder (0)
                        Netscape (1)
printed @ tobymiller.com
(currently rendering CSS for Internet Explorer)(currently rendering CSS for non-Internet Explorer browsers)