Html colors to rgb array

2011-01-04

A small simple snippet to parse a #rrggbb color to [r,g,b] array in js... (or #rrggbbaa to [r,g,b,a]) It uses a combination of regular expressions and Array#map to do it's voodoo. I think it's an elegant solution. I wonder what I'll think of it in a few years ;)

Note that the slice(1) is required to remove the first element of the array, which is the entire match. Due to the use of Array#map (and specifically, the function callback) as well as a regular expression, this is by far the fastest method of doing this.

Code: (js)
var toRgbArray = function(c){
// assumes c is a color in hex format: #rrggbb
var rgb = /#(..)(..)(..)/.exec(c).slice(1).map(function(o){return parseInt(o,16);});
// now rgb is an array with [r,g,b]
return rgb;
};

Of course, the same can be done for rgba...

Code: (js)
var toRgbaArray = function(c){
// assumes c is a color in hex format: #rrggbbaa
var rgb = /#(..)(..)(..)(..)/.exec(c).slice(1).map(function(o){return parseInt(o,16);});
// now rgb is an array with [r,g,b,a]
return rgb;
};

You can combine them (make the last group in the regex optional) and for production you would need to add input checking code (like shorthand notation #rgb would fail) but this is the general idea. It's nice and clean. Don't you just love the "new" array methods? :)

I guess a faster implementation would probably be something like

Code: (js)
var faster = function(c){
var arr = [];
arr[0] = parseInt(c[1]+c[2], 16);
arr[1] = parseInt(c[3]+c[4], 16);
arr[2] = parseInt(c[5]+c[6], 16);
//arr[0] = parseInt(c[7]+c[8], 16);
return arr;
};

(And yes, I'm sure there are faster hacks around :))