Last active
December 4, 2015 20:10
-
-
Save niccai/28f06b9050ea1502eaa8 to your computer and use it in GitHub Desktop.
Takes in a hex value and converts it to RGB.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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