Skip to content

Instantly share code, notes, and snippets.

@cristian-frumusanu
Created September 20, 2019 08:02
Show Gist options
  • Save cristian-frumusanu/b25a7deabf4c03969ed9a5cacae4d773 to your computer and use it in GitHub Desktop.
Save cristian-frumusanu/b25a7deabf4c03969ed9a5cacae4d773 to your computer and use it in GitHub Desktop.
RGB to HEX
const _rgb2hex = ( orig ) => {
let rgb = orig.replace(/\s/g, '').match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i),
alpha = (rgb && rgb[4] || "").trim(),
hex = rgb ?
(rgb[1] | 1 << 8).toString(16).slice(1) +
(rgb[2] | 1 << 8).toString(16).slice(1) +
(rgb[3] | 1 << 8).toString(16).slice(1) : orig;
if ( alpha !== '' && alpha < 1 ) {
hex += ' ' + alpha;
}
return '#' + hex.toUpperCase();
};
export _rgb2hex;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment