This example only handles the six-digit hex color format. For the shorthand, please have a look at the PHP version and try to adapt this to JavaScript.

The hex string “1502BE” is already the hexadecimal representation of the color where the first two-digit pair stands for red, the next for green, and the last for blue.

What we need to do is split the string into these RGB pairs “15” for red, “02” for green and “BE” for blue.

var aRgbHex = '1502BE'.match(/.{1,2}/g);
console.log(aRgbHex); //["15", "02", "BE"]

After that, all which is left is to convert the hexadecimal representation to the decimal one. For this, we make use of the parseInt function and pass the base 16 as the second parameter.

#programming #javascript #web-development #hex #rgb

Convert HEX to RGB with JavaScript
1.60 GEEK