get rgb from hex javascript code example
Example 1: javascript rgb to hex
function rgbToHex(r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
function hexToRgb(hex) {
var result = /^#?([a-fd]{2})([a-fd]{2})([a-fd]{2})$/i.exec(hex);
if(result){
var r= parseInt(result[1], 16);
var g= parseInt(result[2], 16);
var b= parseInt(result[3], 16);
return r+","+g+","+b;
}
return null;
}
console.log(rgbToHex(10, 54, 120));
console.log(hexToRgb("#0a3678"));
Example 2: convert hex code to rgb javascript
function hexToRgb(hex){
var result = /^#?([a-f\d]{2}])([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16);
g: parseInt(result[2], 16);
b: parseInt(result[3], 16);
} : null;
}
var hex = "#0a3678";
console.log(hexToRgb(hex).r+","+hexToRgb(hex).g+","+hexToRgb(hex).b);
Example 3: typescript convert color to rgb
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
alert(rgbToHex(0, 51, 255));