JavaScript

How to Convert RGB to HEX in JavaScript

Photo editing programs mostly represent colors in the RGB (Red Green Blue) model, ranging from 0 to 255. In case you want to utilize any specific color as an HTML element’s background, it is required to get the hexadecimal representation of the selected RGB value. Many online RGB to HEX color converters can perform this functionality using JavaScript.

This blog will demonstrate the method of converting RGB to HEX in JavaScript.

How to Convert RGB to HEX in JavaScript?

In JavaScript, you can utilize the “toString()” method for converting RGB to HEX. The toString() method takes the base “16” as a parameter for converting the specified RGB value into hexadecimal and returns its string representation.

Go through the following example for a better understanding of the above concept.

Example: Using “toString()” Method to Convert RGB to HEX in JavaScript

Firstly, we will define a function named “valueToHex()” and pass “c” as an argument to it. Then, convert it using the “toString()” method and pass “16” as the required base of the string. This function will return the converted RGB to Hex value stored in “hex” variable:

function valueToHex(c) {

  var hex = c.toString(16);

  return hex

}

Next, we will define a “rgbToHex()” function taking “r”, “g”, “b” values as arguments. For converting each value, call the “valueToHex()” method:

function rgbToHex(r, g, b) {

  return(valueToHex(r) + valueToHex(g) + valueToHex(b));

}

Finally, call the “rgbToHex()” function and place the RGB values in order to get the desired converted hexadecimal values:

console.log("The converted hexadecimal values are:")

console.log(rgbToHex(12, 51, 255));

In our case, we have passed “12”, “51”, and “255” as RGB which is converted to “c33ff” HEX value:

We have provided the simplest method for converting “RGB” to “HEX” in JavaScript.

Conclusion

To convert RGB to HEX in JavaScript, you can use the “toString()” method in a user-defined RGB to HEX conversion function. This function will take each RGB value one by one and call the toString() method to convert it to HEX by specifying the base as “16”. After doing so, it returns the converted RGB to the HEX value. This blog guided you about the procedure to convert RGB to HEX in JavaScript.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.