Implement a function in JavaScript that converts the HEXA color codes to RGB numbers.
Example
Input: "#ff33ff" Output: { "r": 255, "g": 51, "b": 255 }
Hexadecimal uses 16 unique symbols, representing values as โ0 โ 9โ for values between 0 โ 9 and โA โ Fโ or โa โ fโ for values between โ10 โ 15โ.
RGB format is a combination of three colors, red, green, and blue in the range of 0 โ 255. A hex color code is the hexadecimal representation of the RGB numbers.
There are multiple ways in which we can convert the HEXA color codes to RGB numbers.
Appraoch 1. Using slice() method.
A HEXA color code '#ff33ff'
starts with '#'
followed by six alpha-numberic characters ff,33,ff
, two of them each representing, R, G, & B.
We can use the slice()
to get the two number and then use parseInt() method that accepts a radix value and convert the string to number.
const hex2rgb = (hex) => { const r = parseInt(hex.slice(1, 3), 16); const g = parseInt(hex.slice(3, 5), 16); const b = parseInt(hex.slice(5, 7), 16); // return {r, g, b} return { r, g, b }; } console.log(hex2rgb("#ff33ff")); /* { "r": 255, "g": 51, "b": 255 } */
In case we are given a short form of Hexa code like #f3f
, we will have to convert it to the original form.
//create full hex const fullHex = (hex) => { let r = hex.slice(1,2); let g = hex.slice(2,3); let b = hex.slice(3,4); r = parseInt(r+r, 16); g = parseInt(g+g, 16); b = parseInt(b+b, 16); // return {r, g, b} return { r, g, b }; } //convert hex to rgb const hex2rgb = (hex) => { if(hex.length === 4){ return fullHex(hex); } const r = parseInt(hex.slice(1, 3), 16); const g = parseInt(hex.slice(3, 5), 16); const b = parseInt(hex.slice(5, 7), 16); // return {r, g, b} return { r, g, b }; } console.log(hex2rgb("#f3f")); /* { "r": 255, "g": 51, "b": 255 } */
Appraoch 2. Using regex.
The match() method of string accepts a regex and returns the array of matching elements.
We can then use this array to parse the HEXA values to RGB.
const hex2rgb = (hex) => { const rgbChar = ['r', 'g', 'b']; const normal = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i); if (normal) { return normal.slice(1).reduce((a, e, i) => { a[rgbChar[i]] = parseInt(e, 16); return a; }, {}); } const shorthand = hex.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i); if (shorthand) { return shorthand.slice(1).reduce((a, e, i) => { a[rgbChar[i]] = 0x11 * parseInt(e, 16); return a; }, {}); } return null; } console.log(hex2rgb("#ff33ff")); /* { "r": 255, "g": 51, "b": 255 } */ console.log(hex2rgb("#f3f")); /* { "r": 255, "g": 51, "b": 255 } */