Convert RGB/RGBA color to Hex Color
Convert RGB color to Hex Color with javaScript
by Adi Jaya
HTML
<p>
Convert RGB/RGBA to hex:<br>
(opacity of rgba is ignored)
</p>
<p>
<input id="demo" type="text" value="rgba(34, 34, 34, 1)">
<button>Convert</button>
</p>
<p>
Result : <span id="result"></span>
</p>
JavaScript
//Function to convert hex format to a rgb color
function rgb2hex(orig){
var rgb = orig.replace(/\s/g,"").match(/^rgba?\((\d+),(\d+),(\d+)/i);
return (rgb && rgb.length === 4) ? "#" +
("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) : orig;
}
//run with button click [jQuery]
$( "button" ).click(function(){
var hex = rgb2hex( $( "#demo" ).val() );
$( "#result" ).html( hex );
});