rgb(a) to hex
HTML
Convert RGB/RGBA to hex #RRGGBB/#AARRGGBB:<br>
<br>
<input type="text" value="rgba(34, 34, 34, 1)"> <button>Convert</button><br>
<br>
Result: <span class="result"></span>
CSS
body { padding: 20px; }
JavaScript
//Function to convert hex format to a rgb color
function rgb2hex(rgb){
var rgbm = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?((?:[0-9]*[.])?[0-9]+)[\s+]?\)/i);
if (rgbm && rgbm.length === 5){
return "#" +
('0'+Math.round(parseFloat(rgbm[4],10) * 255).toString(16).toUpperCase()).slice(-2) +
("0" + parseInt(rgbm[1],10).toString(16).toUpperCase()).slice(-2) +
("0" + parseInt(rgbm[2],10).toString(16).toUpperCase()).slice(-2) +
("0" + parseInt(rgbm[3],10).toString(16).toUpperCase()).slice(-2);
}else{
var rgbm = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
if (rgbm && rgbm.length === 4){
return "#" +
("0" + parseInt(rgbm[1],10).toString(16).toUpperCase()).slice(-2) +
("0" + parseInt(rgbm[2],10).toString(16).toUpperCase()).slice(-2) +
("0" + parseInt(rgbm[3],10).toString(16).toUpperCase()).slice(-2);
}else{return "cant parse that";}
}
}
$('button').click(function(){
var hex = rgb2hex( $('input').val() );
console.log(hex);
$('.result').html( hex );
});