Sometimes, we want to convert RGB color code to hex with JavaScript.
In this article, we’ll look at how to convert RGB color code to hex with JavaScript.
Convert RGB Color Code to Hex with JavaScript
To convert RGB color code to hex with JavaScript, we can get the RGB number values with the JavaScript string match
method.
Then we can match each value to the corresponding hex number and join them together with the JavaScript string’s join
method.
For instance, we write:
const RGBtoHEX = (color) => {
return "#" + [...color.match(/b(d+)b/g)]
.map((digit) => {
return parseInt(digit)
.toString(16)
.padStart(2, '0')
})
.join('');
};
console.log(RGBtoHEX('rgb(0, 70, 255)'))
We call color.match
with /b(d+)b/g
to match the RGB color values from the color
syring.
Then we use the spread operator to spread the returned results into an array.
Next, we call map
with a callback to parse the numbers into integers, then we convert then to hex strings with toString
and 16 as its argument.
Then we call padStart
to pad the returned string with a zero to make its length 2.
Finally, we call join
to join the mapped strings together.
Therefore, the console log should show "#0046ff"
.
Conclusion
To convert RGB color code to hex with JavaScript, we can get the RGB number values with the JavaScript string match
method.
Then we can match each value to the corresponding hex number and join them together with the JavaScript string’s join
method.