Question

How to Convert RGB to HEX in JavaScript

Show the 2 errors

function ColorToHex(color) {

  var hexadecimal = color.toString(16);

  return hexadecimal.length == 1 ? "0" + hexadecimal : hexadecimal;
}


function ConvertRGBtoHex(red, green, blue) {

  return "#" + ColorToHex(red) + ColorToHex(green) + ColorToHex(blue);

}
console.log(ConvertRGBtoHex(255, 100, 200));

Submit an answer
Answer a question...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Bobby Iliev
Site Moderator
Site Moderator badge
July 11, 2022

Hi there,

The one that you’ve shared looks good! Here is another alternative:

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(0, 105, 255)); // '#0069ff'

Best,

Bobby