This code snippet utilizes a regular expression to extract the brightness value from a given hexadecimal color string, ranging from 0 (black) to 1 (100% white).
function getHexBrightness(hex) {
var regExp = hex.length < 6 ? /^#(([a-f\d]))(([a-f\d]))(([a-f\d]))$/i : /^#([a-f\d])([a-f\d])([a-f\d])([a-f\d])([a-f\d])([a-f\d])$/i;
var result = regExp.exec(hex);
if (result) {
var r = parseInt("" + result[1] + result[2], 16),
g = parseInt("" + result[3] + result[4], 16),
b = parseInt("" + result[5] + result[6], 16),
max = Math.max(r, g, b),
min = Math.min(r, g, b),
l = (max + min) / 2;
return l / 255;
}
return null;
}
// Test
var assert = function (assertion, name) {
$("<p/>").appendTo(document.body).text(name + (assertion ? ' works' : ' fails'))
}
assert(getHexBrightness('#FFFFFF') == 1, 'Uppercase');
assert(getHexBrightness('#ffffff') == 1, 'Lowercase');
assert(getHexBrightness('#fff') == 1, 'Short');
assert(getHexBrightness('#000') == 0, 'Black');
assert(getHexBrightness('invalid') == null, 'Invalid color');
Check out the live version: http://jsfiddle.net/L7PqT/