- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
Advertisements