0

RGB to Hex conversion. My code below converts rgb to hex. There is one problem, r, g or b must be between 0 & 255. At present, if they are below 0, my code does not round them up to 0. I don't know why? Also I need to make sure the max is 255. Any advice please?

function rgb(r, g, b){
var newarr = [];
newarr.push(r, g, b );

var b = newarr.map(function(x){             
 if (isNaN(x) === true ) {
  if ( x  > 0 ) {
  parseInt(x).toString(16); 
  return  (x.length==1) ? "0"+x : x;  
  } else {
  x =  0 ;
  parseInt(x).toString(16); 
  return  (x.length==1) ? "0"+x : x; 
    }
    } else {
    parseInt(x).toString(16); 
  return  (x.length==1) ? "0"+x : x; 
  }

});


var tos = String(b) ;
var fin = tos.replace(/,/g," ");
fint = fin.replace(/\s/g,'');
document.write(fint);
}

rgb('0','0','-14');

This example currently returns: 0000-14

1 Answers1

2

Your code could be much simpler:

function rgb(r, g, b){
    return [r, g, b].map(function(v) {
        return ('0' + 
            Math.min(Math.max(parseInt(v), 0), 255)
            .toString(16)
        ).slice(-2);
    }).join('');
}
hindmost
  • 7,125
  • 3
  • 27
  • 39
  • Thanks, but your code does not add an extra `0` if a single digit number is entered in as r, g, b. For example 4, 45, 155. It must add a zero before the 4, so that it is 04. The Hex code must be 6 characters long. –  Mar 13 '16 at 19:25
  • Thanks, the code is perfect now. I was wondering if you could explain why the slice is used? I don't understand why it is necessary here? I would really appreciate it if you would. Thanks for the help. –  Mar 13 '16 at 19:35
  • 1
    @mattnewbie _I don't understand why it is necessary here?_ It does zero-padding. See [here](http://stackoverflow.com/a/9744576/2118955) for details. BTW: You could choose this answer as "accepted" if it solve your problem. – hindmost Mar 14 '16 at 08:26
  • Thank-you that is very useful to know. –  Mar 17 '16 at 10:43