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:
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:
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(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.