
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 }
- Related Questions & Answers
- RGB color to hexadecimal color JavaScript
- C Program to Change RGB color model to HSV color model
- How to use rgb color codes in tkinter?
- How can RGB color space be converted to a different color space in Python?
- How to pass RGB color values to Python's Matplotlib eventplot?
- Random color generator in JavaScript
- Changing color randomly in JavaScript
- How to set outline color with JavaScript?
- Change Cursor Color with CSS caret-color
- Randomize color by number in JavaScript
- Generating random hex color in JavaScript
- JavaScript to generate random hex codes of color
- How to Change Link Underline Color using text-decoration-color CSS
- HTML Color Styles
- Add hover color to background color of the table row in Bootstrap
Advertisements