One-line functional HEX to RGBA
Supports both short #fff
and long #ffffff
forms.
Supports alpha channel (opacity).
Does not care if hash specified or not, works in both cases.
function hexToRGBA(hex, opacity) {
return 'rgba(' + (hex = hex.replace('#', '')).match(new RegExp('(.{' + hex.length/3 + '})', 'g')).map(function(l) { return parseInt(hex.length%2 ? l+l : l, 16) }).concat(isFinite(opacity) ? opacity : 1).join(',') + ')';
}
examples:
hexToRGBA('#fff') -> rgba(255,255,255,1)
hexToRGBA('#ffffff') -> rgba(255,255,255,1)
hexToRGBA('#fff', .2) -> rgba(255,255,255,0.2)
hexToRGBA('#ffffff', .2) -> rgba(255,255,255,0.2)
hexToRGBA('fff', .2) -> rgba(255,255,255,0.2)
hexToRGBA('ffffff', .2) -> rgba(255,255,255,0.2)
hexToRGBA('#ffffff', 0) -> rgba(255,255,255,0)
hexToRGBA('#ffffff', .5) -> rgba(255,255,255,0.5)
hexToRGBA('#ffffff', 1) -> rgba(255,255,255,1)