Skip to content

Instantly share code, notes, and snippets.

@iremlopsum
Created April 23, 2019 10:53
Show Gist options
  • Save iremlopsum/3511256deb072ec112153fe9be9ede2d to your computer and use it in GitHub Desktop.
Save iremlopsum/3511256deb072ec112153fe9be9ede2d to your computer and use it in GitHub Desktop.
const rgba = (value, opacity) => {
const isHex = hex => {
return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex)
}
const hexToRGB = hex => {
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i
const longHex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b
})
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(longHex)
return result
? `${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(
result[3],
16
)}`
: null
}
if (isHex(value)) {
const rgb = hexToRGB(value)
return `rgba(${rgb}, ${opacity})`
}
console.log('stop sending me not hex values')
return null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment