Skip to content

Instantly share code, notes, and snippets.

@aramk
Created October 2, 2012 04:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aramk/3816183 to your computer and use it in GitHub Desktop.
Save aramk/3816183 to your computer and use it in GitHub Desktop.
JavaScript Hexidecimal Colours
/**
* Converts a hex color string to an array of 3 ints
*/
function hex2RGB(h) {
h = h.replace('#', '');
h = h.length == 3 ? shortHexToLong(h) : h;
if (h) {
var m = h.match(/([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/);
if (m) {
var rgb = [];
for (var i = 1; i < m.length; i++) {
rgb.push(hex2Dec(m[i]));
}
return rgb;
} else {
return null;
}
} else {
return null;
}
}
/**
* Converts a shorthand hex to long. E.g. 'f00' = 'ff0000'
*/
function shortHexToLong(h) {
if (h.length == 3) {
j = '';
for (var i in h) {
j += h[i] + h[i];
}
return j;
} else {
return null;
}
}
/**
* Converts a decimal int to a hex string
*/
function dec2Hex(d) {
return d.toString(16);
}
/**
* Converts a hex string to a decimal int
*/
function hex2Dec(h) {
return parseInt(h,16);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment