Skip to content

Instantly share code, notes, and snippets.

@polotek
Created January 9, 2012 18:58
Show Gist options
  • Save polotek/1584364 to your computer and use it in GitHub Desktop.
Save polotek/1584364 to your computer and use it in GitHub Desktop.
Convert hex colors to rgba
/**
* hex2rgb - function for converting hex colors to rgb(a)
*
* Shout out to http://hex2rgba.devoth.com/
*
* @hex (String) - The hex value. Can be prefixed with "#" or not. Can be
* long format (6 chars) or short format (3 chars)
* @opacity (number between 0 and 1) - This is an optional float value that
* will be used for the opacity
*
* returns (Object) - an object with r, g, and b properties set as numbers
* along with a "css" property representing the css rule as a string
*/
function hex2rgb(hex, opacity) {
hex = (hex + '').trim();
var rgb = null
, match = hex.match(/^#?(([0-9a-zA-Z]{3}){1,3})$/);
if(!match) { return null; }
rgb = {}
hex = match[1];
// check if 6 letters are provided
if (hex.length == 6) {
rgb.r = parseInt(hex.substring(0, 2), 16);
rgb.g = parseInt(hex.substring(2, 4), 16);
rgb.b = parseInt(hex.substring(4, 6), 16);
}
else if (hex.length == 3) {
rgb.r = parseInt(hex.substring(0, 1) + hex.substring(0, 1), 16);
rgb.g = parseInt(hex.substring(1, 2) + hex.substring(1, 2), 16);
rgb.b = parseInt(hex.substring(2, 3) + hex.substring(2, 3), 16);
}
rgb.css = 'rgb' + (opacity ? 'a' : '') + '(';
rgb.css += rgb.r + ',' + rgb.g + ',' + rgb.b;
rgb.css += (opacity ? ',' + opacity : '') + ')';
return rgb;
}
@polotek
Copy link
Author

polotek commented Jan 9, 2012

Yeah I'm not really interested in golfing for the sake of size. Really just looking for other interesting ways to approach this. I think my version is very readable and pretty reliable. It's cross browser too, although map() is the only thing that disqualifies yours. Good speed and low object creation would also be nice. As a general solution the object is most versatile. Honestly my requirements are different. I just thought people might like to golf it a bit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment