My fiddle - http://jsbin.com/pitu/1/edit
I wanted to try an easy hex to rgba conversion. Ever browser I\'ve used renders colors using rgb as default so when using th
Clean TypeScript version:
hexToRGB(hex: string, alpha: string) {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
if (alpha) {
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
} else {
return `rgb(${r}, ${g}, ${b})`;
}
}
Based on @AJFarkas's answer.
Here's a quick function that supports 3, 4, 6 and 8 character color codes:
function hexToRGBA(hex) {
// remove invalid characters
hex = hex.replace(/[^0-9a-fA-F]/g, '');
if (hex.length < 5) {
// 3, 4 characters double-up
hex = hex.split('').map(s => s + s).join('');
}
// parse pairs of two
let rgba = hex.match(/.{1,2}/g).map(s => parseInt(s, 16));
// alpha code between 0 & 1 / default 1
rgba[3] = rgba.length > 3 ? parseFloat(rgba[3] / 255).toFixed(2): 1;
return 'rgba(' + rgba.join(', ') + ')';
}
Here's what it does. It removes any non-hexadecimal characters. If the HEX is shorter than 5 (3 or 4) characters, it doubles each character. It then splits the HEX into pairs of two characters and parses each pair to an integer. If there is an alpha HEX, it's parsed to a float from 0 to 1, otherwise it's defaulted to 1. The RGBA string is then formed by joining the array and returned.
ES6 modern, RegEx free, solution with error checking and constant arrow function, that returns null for errors. If alpha is not given then the default value of one is used:
const hexToRGB = (hex, alpha = 1) => {
let parseString = hex;
if (hex.startsWith('#')) {parseString = hex.slice(1, 7);}
if (parseString.length !== 6) {return null;}
const r = parseInt(parseString.slice(0, 2), 16);
const g = parseInt(parseString.slice(2, 4), 16);
const b = parseInt(parseString.slice(4, 6), 16);
if (isNaN(r) || isNaN(g) || isNaN(b)) {return null;}
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
};
Note: It returns null
for errors. You may replace {return null;}
with a throw statement: {throw "Not a valid hex color!";}
, but then you should call it from within
try-catch
:
hexToRGB("#3454r5") => null
hexToRGB("#345465") => rgba(52, 84, 101, 1)
hexToRGB("#345465", 0.5) => rgba(52, 84, 101, 0.5)
Here's an ES2015+ version that's a little more defensive and handles the shorthand 3-digit syntax.
/*
* Takes a 3 or 6-digit hex color code, and an optional 0-255 numeric alpha value
*/
function hexToRGB(hex, alpha) {
if (typeof hex !== 'string' || hex[0] !== '#') return null; // or return 'transparent'
const stringValues = (hex.length === 4)
? [hex.slice(1, 2), hex.slice(2, 3), hex.slice(3, 4)].map(n => `${n}${n}`)
: [hex.slice(1, 3), hex.slice(3, 5), hex.slice(5, 7)];
const intValues = stringValues.map(n => parseInt(n, 16));
return (typeof alpha === 'number')
? `rgba(${intValues.join(', ')}, ${alpha})`
: `rgb(${intValues.join(', ')})`;
}
Convert HEX with alpha (ahex) in to rgba.
function ahex_to_rba(ahex) {
//clean #
ahex = ahex.substring(1, ahex.length);
ahex = ahex.split('');
var r = ahex[0] + ahex[0],
g = ahex[1] + ahex[1],
b = ahex[2] + ahex[2],
a = ahex[3] + ahex[3];
if (ahex.length >= 6) {
r = ahex[0] + ahex[1];
g = ahex[2] + ahex[3];
b = ahex[4] + ahex[5];
a = ahex[6] + (ahex[7] ? ahex[7] : ahex[6]);
}
var int_r = parseInt(r, 16),
int_g = parseInt(g, 16),
int_b = parseInt(b, 16),
int_a = parseInt(a, 16);
int_a = int_a / 255;
if (int_a < 1 && int_a > 0) int_a = int_a.toFixed(2);
if (int_a || int_a === 0)
return 'rgba('+int_r+', '+int_g+', '+int_b+', '+int_a+')';
return 'rgb('+int_r+', '+int_g+', '+int_b+')';
}
Try it yourself with snippet:
function ahex_to_rba(ahex) {
//clean #
ahex = ahex.substring(1, ahex.length);
ahex = ahex.split('');
var r = ahex[0] + ahex[0],
g = ahex[1] + ahex[1],
b = ahex[2] + ahex[2],
a = ahex[3] + ahex[3];
if (ahex.length >= 6) {
r = ahex[0] + ahex[1];
g = ahex[2] + ahex[3];
b = ahex[4] + ahex[5];
a = ahex[6] + (ahex[7] ? ahex[7] : ahex[6]);
}
var int_r = parseInt(r, 16),
int_g = parseInt(g, 16),
int_b = parseInt(b, 16),
int_a = parseInt(a, 16);
int_a = int_a / 255;
if (int_a < 1 && int_a > 0) int_a = int_a.toFixed(2);
if (int_a || int_a === 0)
return 'rgba('+int_r+', '+int_g+', '+int_b+', '+int_a+')';
return 'rgb('+int_r+', '+int_g+', '+int_b+')';
}
$(function() {
$('#go').click(function() {
$('p b').text(ahex_to_rba($('#hex').val()));
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="hex" type="text" value="#ffaaffaa">
<input id="go" type="button" value="Go">
<p>Result: <b></b></p>
Original Author
And another one based around bit shifting.
// hex can be a string in the format of "fc9a04", "0xfc9a04" or "#fc90a4" (uppercase digits are allowed) or the equivalent number
// alpha should be 0-1
const hex2rgb = (hex, alpha) => {
const c = typeof(hex) === 'string' ? parseInt(hex.replace('#', ''), 16) : hex;
return `rgb(${c >> 16}, ${(c & 0xff00) >> 8}, ${c & 0xff}, ${alpha})`;
};