Skip to content

Instantly share code, notes, and snippets.

@dualcyclone
Created October 7, 2021 13:30
Show Gist options
  • Save dualcyclone/44cac46d4181e30ab9894b983055eccc to your computer and use it in GitHub Desktop.
Save dualcyclone/44cac46d4181e30ab9894b983055eccc to your computer and use it in GitHub Desktop.
Convert hex colour to RGB values, and utility to create a CSS RGBA value from a hex and provided alpha value
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
const rgbRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
/**
* Converts a CSS hex value into an RGB array
*/
export const hexToRgb = (hex: string): number[] | null => {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
const result = rgbRegex.exec(
hex.replace(shorthandRegex, (_, red: string, grn: string, blu: string) => `${red}${red}${grn}${grn}${blu}${blu}`)
);
return result ? result.slice(1).map((tok: string) => parseInt(tok, 16)) : null;
};
/**
* Convert a CSS hex value into a CSS rgba definition
*/
export const hexToRgba = (hex: string, alpha: number | string): string => {
const rgb = hexToRgb(hex);
if (!rgb || !alpha) {
return "";
}
return `rgba(${rgb}, ${alpha})`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment