Let’s say you have the following hexadecimal as a string:
var hex = 'BADA55';
How can you convert it to its equivalent RGB value?
With parseInt()
, you can convert every two characters to its base 16 form:
var BASE = 16;
var r = parseInt(hex.slice(0, 2), BASE);
var g = parseInt(hex.slice(2, 4), BASE);
var b = parseInt(hex.slice(4, 6), BASE);
Then you can simply concatenate them together:
var rgb = 'rgb(' + [r, g, b].join(',') + ')';
hexToRGB()
Here’s a function written in ES5:
var BASE = 16;
function hexToRGB(hex) {
var rgb = '', start = 0, len = hex.length;
for (; start < len; start += 2) {
rgb += parseInt(hex.slice(start, start + 2), BASE);
}
return 'rgb(' + rgb + ')';
}
And an alternative function written in ES6:
const BASE = 16;
const hexToRGB = (hex) => {
const rgb = [0, 2, 4].map((start) => {
return parseInt(hex.slice(start, start + 2), BASE);
});
return `rgb(${rgb.join(',')})`;
}