Report this

What is the reason for this report?

How to Convert RGB to HEX in JavaScript

Posted on July 6, 2022

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));


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!

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.

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

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Start building today

From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.

Dark mode is coming soon.