Skip to content

Instantly share code, notes, and snippets.

@duncanbeevers
Created January 15, 2010 19:10
Show Gist options
  • Save duncanbeevers/278311 to your computer and use it in GitHub Desktop.
Save duncanbeevers/278311 to your computer and use it in GitHub Desktop.
Convert a hex color string to an object representing the red, green, and blue parts
function hex2rgb(hex) {
var c, o = [], k = 0, m = hex.match(
/^#(([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})|([0-9a-f])([0-9a-f])([0-9a-f]))$/i);
if (!m) return {r:0,g:0,b:0};
for (var i = 2, s = m.length; i < s; i++) {
if (undefined === m[i]) continue;
c = parseInt(m[i], 16);
o[k++] = c + (i > 4 ? c * 16 : 0);
}
return {r:o[0], g:o[1], b:o[2]};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment