Published on

How to convert RGB Colors to Hex Color in Javascript

Authors

Recently we've talked about Hex Color to RGB Color

Today, let's see how to do the reverse of that:

const rgb = [41, 127, 58];

const rgbToHex = (rgb) => {
  let hex = "";
  rgb.forEach((color) => {
    // convert number to hexadecimal notation
    // https://nesin.io/blog/convert-number-to-hex-javascript
    let hexVal = color.toString(16);
    hexVal = hexVal.length == 1 ? "0" + hexVal : hexVal;
    hex += hexVal;
  });
  return hex;
}

// rgbToHex(rgb) 👉 '297f3a'

Happy playing-with hex!