Last Updated: February 25, 2016
·
3.271K
· ekidd

Convert Hex Colors to RGB in JS

A few lines of code that can lets you convert a hex code into it's RGB parts.

function convertColor(color) {
  /* Check for # infront of the value, if it's there, strip it */

  if(color.substring(0,1) == '#') {
     color = color.substring(1);
   }

  var rgbColor = {};

  /* Grab each pair (channel) of hex values and parse them to ints using hexadecimal decoding */
  rgbColor.rChannel = parseInt(color.substring(0,2),16);
  rgbColor.gChannel = parseInt(color.substring(2,4),16);
  rgbColor.bChannel = parseInt(color.substring(4),16);

  return rgbColor;
 }

Now you can use the individual channels for whatever you need! Just call the channels from the rgbColor object!