Published on

How to convert CSS Hex Color Code to RGB in Javascript

Authors

CSS Hex color code is just the combination of RGB in hexadecimal.

For example, #297F3A === 29 (Red) + 7F (Green) + 3A (Blue)

In Javascript, we can use parseInt to convert a hex string to a number.

function hexToRGB(hex) {
  // Remove the # character from the beginning of the hex code
  hex = hex.replace("#", "");
  
  // Convert the red, green, and blue components from hex to decimal
  // you can substring instead of slice as well
  const r = parseInt(hex.slice(0, 2), 16);
  const g = parseInt(hex.slice(2, 4), 16);
  const b = parseInt(hex.slice(4, 6), 16);
  
  // Return the RGB value as an object with properties r, g, and b
  return {r, g, b};
}

const color = "#297F3A";
const rgb = hexToRGB(color); // Output: {r: 41, g: 127, b: 58}

Happy converting colors!