Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Last active September 4, 2015 05:24
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 nathansmith/271050 to your computer and use it in GitHub Desktop.
Save nathansmith/271050 to your computer and use it in GitHub Desktop.
Convert colors to RGB
/*
This will change:
"rgba(255, 255, 255)" or "#fff"
Into:
#FFFFFF
*/
// Change RBG into Hex colors.
function parseColor(the_color) {
function toHex(N) {
var hex_range = '0123456789ABCDEF';
if (N === null) {
return '00';
}
N = parseInt(N, 10);
if (N === 0 || isNaN(N)) {
return '00';
}
N = Math.max(0, N);
N = Math.min(N, 255);
N = Math.round(N);
return hex_range.charAt((N - N % 16) / 16) + hex_range.charAt(N % 16);
}
if (the_color.match('#')) {
the_color = the_color.replace('#', '');
if (the_color.length !== 6) {
var R = the_color.slice(0, 1);
var G = the_color.slice(1, 2);
var B = the_color.slice(2, 3);
the_color = R + R + G + G + B + B;
}
}
else if (the_color.match('rgb')) {
the_color = the_color.replace(/rgb\(|\)| /gi, '').split(',');
var RED = the_color[0];
var GREEN = the_color[1];
var BLUE = the_color[2];
the_color = toHex(RED) + toHex(GREEN) + toHex(BLUE);
}
return '#' + the_color.toUpperCase();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment