Convert Hex to RGBA
//If you write your own code, remember hex color shortcuts (eg., #fff, #000)function hexToRgbA(hex){ var 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(',')+',1)'; } throw new Error('Bad Hex');}hexToRgbA('#fbafff')/* returned value: (String)rgba(251,175,255,1)*/
@ElDoRado1239 has the right idea, but there's also a cleaner way:
function hexToRGB(hex, alpha) { var r = parseInt(hex.slice(1, 3), 16), g = parseInt(hex.slice(3, 5), 16), b = parseInt(hex.slice(5, 7), 16); if (alpha) { return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")"; } else { return "rgb(" + r + ", " + g + ", " + b + ")"; }}hexToRGB('#FF0000', 0.5);
ES6 function for only handling 6 character hex with or without the '#':
const hex2rgba = (hex, alpha = 1) => { const [r, g, b] = hex.match(/\w\w/g).map(x => parseInt(x, 16)); return `rgba(${r},${g},${b},${alpha})`;};
Usage:
hex2rgba('#af087b', .5) // returns: rgba(175,8,123,0.5)hex2rgba('af087b', .5) // returns: rgba(175,8,123,0.5)hex2rgba('af087b') // returns: rgba(175,8,123,1)