How to convert RGB to hex in Node.js

4 Answers

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

 



answered Dec 30, 2021 by avibootz
0 votes
function rgbToHex(r, g, b) {
    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
const rgbToHex = (r, g, b) => '#' + [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
0 votes
const rgbToHex = (r, g, b) => '#' + [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

Related questions

2 answers 340 views
340 views asked Dec 30, 2021 by avibootz
1 answer 122 views
122 views asked Jan 31, 2023 by avibootz
1 answer 89 views
1 answer 93 views
1 answer 109 views
1 answer 102 views
102 views asked Nov 18, 2024 by avibootz
...