Skip to content

Instantly share code, notes, and snippets.

@anthonyec
Last active September 25, 2024 14:12
Show Gist options
  • Select an option

  • Save anthonyec/5361441995226bef98d6fddd4e67c8b7 to your computer and use it in GitHub Desktop.

Select an option

Save anthonyec/5361441995226bef98d6fddd4e67c8b7 to your computer and use it in GitHub Desktop.
CSS RGB(A) to Hexadecimal
function RGBtoHEX(color: string): string {
const channels = color
// Remove white space.
.trim()
.replace(/\s/gu, "")
// Remove "rgb" or "rgba".
.replace(/rgba?/u, "")
// Remove brackets.
.replace("(", "")
.replace(")", "")
// Split channels into numbers.
.split(",")
.map(number => parseInt(number))
const [r = 0, g = 0, b = 0] = channels
// Pad left hex numbers. E.g "0" becomes "00".
const [hexR, hexG, hexB] = channels.map(channel => {
const hex = channel.toString(16)
return hex.length % 2 ? "0" + hex : hex
})
return `#${hexR}${hexG}${hexB}`.toUpperCase()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment