0

I have an array of hex colors like this:

var hexColors = [
    "#ffffff",
    "#ffffff",
    "#ffffff",
    "#f3f3f3",
    "#f3f3f3",
    "#f3f3f3"];

I want to turn it into this:

var rgbColors = new Array(
[62,35,255],
[60,255,60],
[255,35,98],
[45,175,230],
[255,0,255],
[255,128,0]);

using this function :

 function hexToRgb(hex) {
 var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
 hex = hex.replace(shorthandRegex, function(m, r, g, b) {
    return r + r + g + g + b + b;
 });
 var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
 return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
 } : null;
}

How can I do? Thanks!

2 Answers2

3

You overcomplicate this: there's no need to run over the target string with regex twice. It's enough to extract all the info at the first iteration. Like this:

function hexToRgb(hex) {
  var res = hex.match(/[a-f0-9]{2}/gi);
  return res && res.length === 3
    ? res.map(function(v) { return parseInt(v, 16) })
    : null;
}

The function is ready to be use in another .map, giving the results you want.

var hexColors = [
    "#ffffff",
    "#ffffff",
    "#ffffff",
    "#f3f3f3",
    "#f3f3f3",
    "#f3f3f3"
];
var rgbColors = hexColors.map(hexToRgb);

Demo

raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • My god! I still have a lot to study and learn! It works perfectly! Thank u so much! – Roberto Di Marco Sep 14 '14 at 08:34
  • How would you go about changing this function to do the opposite? changing an rgb array i.e `[255, 255, 255]` into `#FFFFFF` –  Jan 07 '16 at 04:58
2
var hex = 'ffaadd';   
var rgb = parseInt(hex, 16);    

var red   = (rgb >> 16) & 0xFF;   
var green = (rgb >> 8) & 0xFF;     
var blue  = rgb & 0xFF;   

Bit Operator makes it more smart ass, in both efficiency and readability.

noru
  • 526
  • 3
  • 15