Sometimes, we want to convert hex to RGBA with JavaScript.
In this article, we’ll look at how to convert hex to RGBA with JavaScript.
How to convert hex to RGBA with JavaScript?
To convert hex to RGBA with JavaScript, we call the string match
method.
For instance, we write
const hex2rgba = (hex, alpha = 1) => {
const [r, g, b] = hex.match(/\w\w/g).map((x) => parseInt(x, 16));
return `rgba(${r},${g},${b},${alpha})`;
};
to define the hex2rgba
function.
In it, we call hex.match
with a regex to match groups of 2 digits.
Then we call map
on the returned array with a callback to parse the hex number with parseInt
called with x
and 16.
Finally, we return the string with the r
, g
, b
and alpha
values inside.
Conclusion
To convert hex to RGBA with JavaScript, we call the string match
method.