Fortunately, color values ββin HTML5 are only valid if they are in the #XXXXXX format ( rgb(...) and #XXX are not valid). We can use this to our advantage, since we always know exactly where the RGB positions will be in the resulting value:
#XXXXXX #RRGGBB
To convert this to rgb(...) , we just need to cross out the # character and convert the values ββof RR , GG and BB to decimal numbers:
// #XXXXXX -> ["XX", "XX", "XX"] var value = value.match(/[A-Za-z0-9]{2}/g); // ["XX", "XX", "XX"] -> [n, n, n] value = value.map(function(v) { return parseInt(v, 16) }); // [n, n, n] -> rgb(n,n,n) return "rgb(" + value.join(",") + ")";
And with the beauty of JavaScript, we can do all this on one line of code:
return "rgb(" + "#FF0000".match(/[A-Za-z0-9]{2}/g).map(function(v) { return parseInt(v, 16) }).join(",") + ")"; -> "rgb(255,0,0)"
source share