Skip to content

Instantly share code, notes, and snippets.

@AdamGerthel
Last active May 11, 2019 18:46
Show Gist options
  • Save AdamGerthel/1551e70de378eac2af30dd7a571385cb to your computer and use it in GitHub Desktop.
Save AdamGerthel/1551e70de378eac2af30dd7a571385cb to your computer and use it in GitHub Desktop.
Hex to RGBa (Javascript)
const hexToRgbA = (hex, alpha = 1) => {
let c
if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
c = hex.substring(1).split('')
if (c.length== 3) {
c = [c[0], c[0], c[1], c[1], c[2], c[2]]
}
c = '0x' + c.join('')
return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',') + ',' + alpha + ')'
}
throw new Error('Bad Hex')
}
hexToRgbA('2A2F33') // 'rgba(44,47,51,1)'
hexToRgbA('2A2F33', 0.5) // 'rgba(44,47,51,0.5)'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment