Skip to content

Instantly share code, notes, and snippets.

@ashblue
Created August 21, 2012 00:34
Show Gist options
  • Save ashblue/3409878 to your computer and use it in GitHub Desktop.
Save ashblue/3409878 to your computer and use it in GitHub Desktop.
Convert hexidecimal colors to RGB (red, green, blue) format. Includes support for hex shorthand '#000'
function hexToRGB(hex) {
// Strip '#'
var nums = hex.slice(1);
// If they pass in a shorthand hexcode convert it
if (nums.length === 3) {
var numStack = '';
for (var i = 0; i < nums.length; i++) {
numStack += nums.charAt(i) + nums.charAt(i);
}
nums = numStack;
}
// Send back converted value
return {
red: parseInt(nums.substring(0, 2), 16),
green: parseInt(nums.substring(2, 4), 16),
blue: parseInt(nums.substring(4, 6), 16)
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment