Two JavaScript functions to convert rgb colour values to hex colour values and then second one converts hex colours values back to rgb. This is very useful for working with html colours and changing colours dynamically using jQuery.
Function to Convert RGB to HEX
function rgb2hex(rgb){
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
return "#" +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3],10).toString(16)).slice(-2);
}
Function to Convert RGB to Hex (version 2)
function RGB2Color(r,g,b)
{
return '#' + this.byte2Hex(r) + this.byte2Hex(g) + this.byte2Hex(b);
}
function byte2Hex (n)
{
var nybHexString = "0123456789ABCDEF";
return String(nybHexString.substr((n >> 4) & 0x0F,1)) + nybHexString.substr(n & 0x0F,1);
}
Function to Convert Hex to RGB
function hexToRgb(h)
{
var r = parseInt((cutHex(h)).substring(0,2),16), g = ((cutHex(h)).substring(2,4),16), b = parseInt((cutHex(h)).substring(4,6),16)
return r+''+b+''+b;
}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
//usage
console.log(hexToRgb("#FFFFFF"));
Function to Convert HEX to RGB (PHP)
function hex2rgb( $colour ) {
if ( $colour[0] == '#' ) {
$colour = substr( $colour, 1 );
}
if ( strlen( $colour ) == 6 ) {
list( $r, $g, $b ) = array( $colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5] );
} elseif ( strlen( $colour ) == 3 ) {
list( $r, $g, $b ) = array( $colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2] );
} else {
return false;
}
$r = hexdec( $r );
$g = hexdec( $g );
$b = hexdec( $b );
return array( 'red' => $r, 'green' => $g, 'blue' => $b );
}






You state that this can be used to change colors dynamically. While I’ve had to change colors a few times I’ve never had to convert RGB to Hex or Hex to RGB dynamically. Can you please explain a scenario where you’d want or need to do this? Not questioning your statement, just trying to understand. Thanks.
@RGB to Hex – yes i agree most apps these days take both rgb and hex but sometimes when your programming, especially front-end applications its handy to know how to convert between them quickly. Nowadays css obviously accepts both RGB and Hex.
shame the hex to RGB is in php… not jquery
@Owen,
Great spot mate I must have been tired oO! I’ve fixed it up now.
Cheers,
Sam