Hexadecimal color to RGB color JavaScript



We are required to write a JavaScript function that takes in a hexadecimal color and returns its RGB representation.

The function should return an object containing the respective values of red green and blue color −

For example:

hexToRgb('#0080C0') should return 0, 128, 192

The code for this will be −

const hex = '#0080C0'; const hexToRGB = hex => {    let r = 0, g = 0, b = 0;    // handling 3 digit hex    if(hex.length == 4){       r = "0x" + hex[1] + hex[1];       g = "0x" + hex[2] + hex[2];       b = "0x" + hex[3] + hex[3];       // handling 6 digit hex    }else if (hex.length == 7){       r = "0x" + hex[1] + hex[2];       g = "0x" + hex[3] + hex[4];       b = "0x" + hex[5] + hex[6];    };    return{       red: +r,       green: +g,       blue: +b    }; } console.log(hexToRGB(hex));

Following is the output on console −

{ red: 0, green: 128, blue: 192 }
Updated on: 2020-10-09T11:08:01+05:30

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements