Skip to content

Instantly share code, notes, and snippets.

@rijkvanzanten
Created March 26, 2017 10:07
Show Gist options
  • Save rijkvanzanten/ff6e723abc6caf3e48a95626177440ef to your computer and use it in GitHub Desktop.
Save rijkvanzanten/ff6e723abc6caf3e48a95626177440ef to your computer and use it in GitHub Desktop.
Converts hex value to RGB(a) values
/**
* Converts hex value (without #) to rgb(a) object
* @param {String} hex 3, 6 or 8 digit hex (without #)
* @return {Object} rgba values
*/
function convertHexToRGB(hex) {
var fullHex = hex;
var rgba = {};
if(hex.length === 3) {
// Convert length === 3 to length === 6
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
fullHex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
}
if(hex.length === 8) {
// Save alpha value to object and remove last two characters (alpha)
rgba.a = convertRange(parseInt(hex.substring(hex.length - 2), 16), { min: 0, max: 255 }, { min: 0, max: 1 });
fullHex = hex.substring(0, hex.length - 2);
}
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(fullHex);
rgba.r = parseInt(result[1], 16);
rgba.g = parseInt(result[2], 16);
rgba.b = parseInt(result[3], 16);
return rgba;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment