Skip to content

Instantly share code, notes, and snippets.

@niccai
Last active December 4, 2015 20:10
Show Gist options
  • Save niccai/28f06b9050ea1502eaa8 to your computer and use it in GitHub Desktop.
Save niccai/28f06b9050ea1502eaa8 to your computer and use it in GitHub Desktop.
Takes in a hex value and converts it to RGB.
hexToRGB (hex) {
if (!hex) {
return '';
}
// remove the hash
hex = hex.replace('#', '');
// if shorthand, expand it
if (hex.length < 6) {
let shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
}
// convert to RGB
hex = parseInt(hex, 16);
let r = hex >> 16;
let g = hex >> 8 & 0xFF;
let b = hex & 0xFF;
return [r, g, b].join();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment