Skip to content

Instantly share code, notes, and snippets.

@iremlopsum
Last active June 12, 2018 18:14
Show Gist options
  • Select an option

  • Save iremlopsum/0d6fb5a10cc2f209488b6a565b548c85 to your computer and use it in GitHub Desktop.

Select an option

Save iremlopsum/0d6fb5a10cc2f209488b6a565b548c85 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;
}
export default rgba;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment