Return to Snippet

Revision: 29379
at July 28, 2010 06:26 by Sverri

Initial Code
function hex2rgb(hex) {
  if (hex[0]=="#") hex=hex.substr(1);
  if (hex.length==3) {
    var temp=hex; hex='';
    temp = /^([a-f0-9])([a-f0-9])([a-f0-9])$/i.exec(temp).slice(1);
    for (var i=0;i<3;i++) hex+=temp[i]+temp[i];
  var triplets = /^([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i.exec(hex).slice(1);
  return {
    red:   parseInt(triplets[0],16),
    green: parseInt(triplets[1],16),
    blue:  parseInt(triplets[2],16)

// Example
var hex = "#fA0";
var rgb = hex2rgb(hex);
document.write("<pre>"+hex+" \u2192 rgb("","","")</pre>");

Initial URL

Initial Description
Converts and returns the RGB equivalent of a HEX value. The RGB values are returned as an object, with the members "red", "green" and "blue". See the example in code snippet if you do not know how to use the function.

Initial Title
HEX to RGB Converter

Initial Tags

Initial Language