How to Convert RGB to Hex and Vice Versa in JavaScript

Colors play a crucial role in any web development project.

The most widely used color format on the web is RGB (Red, Green, Blue) and HEX (Hexadecimal) codes.

RGB values range from 0 to 255, while HEX values range from 00 to FF.

These values represent the intensity of the Red, Green, and Blue components in the color.

In this tutorial, we’ll discuss how to convert RGB to HEX and vice versa in JavaScript.


Converting RGB to HEX

To convert RGB to HEX in JavaScript, we can write a function that takes three parameters representing the red, green, and blue components of the color.

Here’s the code:

function rgbToHex(r, g, b) {
  return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

In the above code, we first convert the RGB values to a single integer using bit shifting.

The toString(16) method is used to convert the resulting integer to a hexadecimal string.

The slice(1) method is used to remove the first character (1) from the resulting string.

Converting HEX to RGB

To convert HEX to RGB in JavaScript, we can write a function that takes a HEX code as a parameter.

Here’s the code:

function hexToRgb(hex) {
  var r = parseInt(hex.substring(0,2), 16);
  var g = parseInt(hex.substring(2,4), 16);
  var b = parseInt(hex.substring(4,6), 16);
  return "rgb(" + r + ", " + g + ", " + b + ")";
}

In the above code, we first use the substring method to extract the red, green, and blue components from the HEX code.

The parseInt method is used to convert the resulting hexadecimal strings to integers.

Finally, we return the RGB code in the rgb(r, g, b) format.


Conclusion

In this tutorial, we discussed how to convert RGB to HEX and vice versa in JavaScript.

We wrote functions to perform the conversions, which can be easily integrated into any web development project.

Understanding how to convert colors is an essential skill for any web developer, and we hope this tutorial has provided a good starting point for you.

Editorial Team
Editorial Team

Programming Cube website is a resource for you to find the best tutorials and articles on programming and coding.