# 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 = parseInt(c+c, 16); arr = parseInt(c+c, 16); arr = parseInt(c+c, 16); //arr = parseInt(c+c, 16); return arr;};`
(And yes, I'm sure there are faster hacks around :))
{"ft_lang_label":"__label__en","ft_lang_prob":0.80611163,"math_prob":0.9597628,"size":1572,"snap":"2020-24-2020-29","text_gpt3_token_len":457,"char_repetition_ratio":0.11288265,"word_repetition_ratio":0.08730159,"special_character_ratio":0.32315522,"punctuation_ratio":0.20273973,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9587194,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-06-07T02:31:40Z\",\"WARC-Record-ID\":\"<urn:uuid:35cd3ffb-8719-40ae-a446-0b8214099569>\",\"Content-Length\":\"16874\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:e0811809-008b-4f71-b0e8-d75dd84f687d>\",\"WARC-Concurrent-To\":\"<urn:uuid:d196fb91-9344-4fa7-850e-a9de3d0c40ca>\",\"WARC-IP-Address\":\"208.113.154.88\",\"WARC-Target-URI\":\"https://pvdz.ee/notes/121\",\"WARC-Payload-Digest\":\"sha1:O7CWNYKNNK5I4FIMKAI74AOKXDLT5CEN\",\"WARC-Block-Digest\":\"sha1:APU4TOJHWJQKNZG74HUSOVXCWQYRQFXW\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-24/CC-MAIN-2020-24_segments_1590348523476.97_warc_CC-MAIN-20200607013327-20200607043327-00061.warc.gz\"}"}