In this article, we will learn how to convert a HEX color string like "1502BE" to the RGB Version "21, 2, 190".
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.
var aRgbHex = '1502BE'.match(/.{1,2}/g);
var aRgb = [
parseInt(aRgbHex[0], 16),
parseInt(aRgbHex[1], 16),
parseInt(aRgbHex[2], 16)
];
console.log(aRgb); //[21, 2, 190]
Once we wrote that, we could also move our code to a prototype function so we can execute it on any string.
String.prototype.convertToRGB = function(){
var aRgbHex = this.match(/.{1,2}/g);
var aRgb = [
parseInt(aRgbHex[0], 16),
parseInt(aRgbHex[1], 16),
parseInt(aRgbHex[2], 16)
];
return aRgb;
}
console.log('1502BE'.convertToRGB()); //[21, 2, 190]
Additionally, we should add a check that the string length is 6 to avoid users passing HEX colors in the shorthand format.
String.prototype.convertToRGB = function(){
if(this.length != 6){
throw "Only six-digit hex colors are allowed.";
}
...
String.prototype.convertToRGB = function(){
if(this.length != 6){
throw "Only six-digit hex colors are allowed.";
}
var aRgbHex = this.match(/.{1,2}/g);
var aRgb = [
parseInt(aRgbHex[0], 16),
parseInt(aRgbHex[1], 16),
parseInt(aRgbHex[2], 16)
];
return aRgb;
}
console.log('1502BE'.convertToRGB());
console.log('ff0000'.convertToRGB());
console.log('f00'.convertToRGB());
[21, 2, 190]
[255, 0, 0]
Only six-digit hex colors are allowed.