Javascript automatically converts hexadecimal values

advertisements

This question already has an answer here:

  • How to get hex color value rather than RGB value? 16 answers

Currently I am heaving problems using this really simple bit of code: field.style.backgroundColor="#ffffff"; Till now it has worked fine for me, but just recently I noticed that in webkit the hex values is always converted to rgb values like rgb(255, 255, 255). Usually that wouldn't be a problem, but I need the hex values later on in a php script creating an image. And converting them back just slows down the whole process. So my really basic question is how can I avoid getting those annoying rgb values.


You can split the value into it's parts, convert each number to hexidecimal, then return a formatted string, e.g.:

// convert rgb colour values to hex, e.g. rgb(255, 255, 255) to #ffffff;
function rgbToHex(rgb) {
  var re = /^rgb\(.*\)$/;
  var bits;
  function z(n){return (n<10?'0':'') + n;}

  if (re.test(rgb)) {
    bits = rgb.match(/\d+/g);
    return '#' + z((+bits[0]).toString(16)) +
                 z((+bits[1]).toString(16)) +
                 z((+bits[2]).toString(16));
  }
  return rgb;
}

alert(rgbToHex('rgb(255, 255, 255)')); // #ffffff
alert(rgbToHex('rgb(0, 0, 0)')); // #000000
alert(rgbToHex('rgb(100, 230, 90)')); // #64e65a

You might need an i flag on the test regular expression in case some browsers return "RGB(…)".

Edit

Based on Xotic750's post, the z function should be:

function z(n){return (n.length == 1?'0':'') + n;}

A less strict regular expression may suit too:

  var re = /^rgb/i;

The other fails are a case of garbage in, garbage out. The regular expression can be modified to allow a space in "rgb (" if required. An updated version is:

function rgbToHex(rgb) {
    var re = /^rgb/i;
    var bits = rgb.match(/\d+/g);;

    function z(n) {
        return (n.length == 1? '0' : '') + n;
    }

    if (re.test(rgb) && bits.length == 3) {
        return '#' + z((+bits[0]).toString(16))
                   + z((+bits[1]).toString(16))
                   + z((+bits[2]).toString(16));
    }
    return rgb;
}

The only choice left is if the test fails, should it return the original string or undefined?