Category : JavaScript

How to Convert Hex Colors to RGB

How to Convert Hex Colors to RGB

Before we start to write code and convert our colors, we need to understand both systems’ notations, so let’s begin!

Hex Color Notation

For Hex colors, we have the following pattern:

RRGGBB

where RR represents red color, GG green color, and BB blue color. Each of these chunks is a hexadecimal number.

RGB Color Notation

For RGB colors, we have something like this:

(R, G, B)

where similarly, R stands for red, G for green, and B for blue. R, G, and B are also numbers, but in this case, just regular decimal numbers in the range from 0 to 255.

Hex to RGB

Keeping in mind the details of both notations and information about which number systems we are dealing with, it’s quite easy to conclude that we simply need to transform hexadecimal numbers to decimal for each color channel red, green, and blue. In JavaScript for this purpose, we can just parseInt() function. The function has 2 parameters where the first parameter is the value to parse, and the second one should be a number in the range from 2 to 36, which represents the base of the number (radix).

parseInt(string [, radix])

Final Implementation

const HEX_COLOR_REGEXP = /^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;

// supports only normal hex color notation
const hexToRgb = (hex) => {
  const result = HEX_COLOR_REGEXP.exec(hex);

  if (!result) {
    return null;
  }

  return {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16),
  };
};