RGB to hex

OSCC · JavaScript, String, Math · Nov 3, 2020

Converts the values of RGB components to a hexadecimal color code.

const RGBToHex = (r, g, b) =>
  ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
RGBToHex(255, 165, 1); // 'ffa501'

Recommended snippets & collections

  • Working with color in JavaScript requires some understanding of color formats and conversions. Luckily, this snippet collection's got you covered.

  • Hex to RGB

    JavaScript, String

    Converts a color code to an rgb() or rgba() string if alpha value is provided.

  • RGB to object

    JavaScript, String

    Converts an rgb() color string to an object with the values of each color.

  • Extend hex value

    JavaScript, String

    Extends a 3-digit color code to a 6-digit color code.