How to convert RGB to hex in TypeScript

4 Answers

0 votes
function rgbToHex(r: number, g: number, b: number) {
  	return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

console.log(rgbToHex(250, 152, 5));




/*
run:

"#fa9805" 

*/

 



answered Dec 30, 2021 by avibootz
0 votes
function getHex(n: number) {
    const hex = n.toString(16);

    return hex.length == 1 ? "0" + hex : hex;
}
 
function rgbToHex(r: number, g: number, b: number) {
    return "#" + getHex(r) + getHex(g) + getHex(b);
}
 
console.log(rgbToHex(250, 152, 5));
 
 
 
 
 
/*
run:
 
"#fa9805"
 
*/

 



answered Dec 30, 2021 by avibootz
0 votes
const rgbToHex = (r: number, g: number, b: number) => '#' + [r, g, b].map(x => {
    const hex = x.toString(16)
    
    return hex.length === 1 ? '0' + hex : hex
}).join('')
 
console.log(rgbToHex(250, 152, 5));
  
  
  
  
/*
run:
  
"#fa9805" 
  
*/

 



answered Dec 31, 2021 by avibootz
edited Apr 10, 2024 by avibootz
0 votes
const rgbToHex = (r: number, g: number, b: number) => '#' + [r, g, b]
    .map(x => x.toString(16).padStart(2, '0')).join('')
 
console.log(rgbToHex(0, 252, 5)); 
 
  
  
  
  
/*
run:
  
"#00fc05" 
  
*/

 



answered Dec 31, 2021 by avibootz
edited Apr 10, 2024 by avibootz

Related questions

2 answers 508 views
1 answer 200 views
1 answer 185 views
1 answer 172 views
...