Converting hexadecimal RGB code to decimal with a bookmarklet

Many applications use the default Windows colour picker which unfortunately, doesn’t support hexa codes. Use this bookmarklet to convert and copy the decimal values from your browser to the picker. No need to bullshit around, here’s the thing :-)

Drag this onto your bookmark toolbar:
RGB hex2dec

Here’s the code for the curious souls out there. Nothing interesting. Just using built-in functionality of parseInt().

  1.  
  2.   hexa = prompt(‘Enter a hexadecimal RGB code (# optional):’);
  3.   if (hexa.charAt(0) == ‘#’) {
  4.     hexa = hexa.substring(1,7);
  5.   }
  6.  
  7.   var r = parseInt(hexa.substring(0,2), 16);
  8.   var g = parseInt(hexa.substring(2,4), 16);
  9.   var b = parseInt(hexa.substring(4,6), 16);
  10.  
  11.   prompt(hexa, r + ‘ ‘ + g + ‘ ‘ + b);
  12.  

One Response to “Converting hexadecimal RGB code to decimal with a bookmarklet”

  1. T.J. Crowder says:

    Neat! Maybe handle three-character versions as well, and allow repeated use, e.g. (live copy | source):

    var hexa, rgb;
    
    hexa = prompt('Enter a hexadecimal RGB code (# optional):');
    while (hexa) {
      if (hexa.charAt(0) === '#') {
        hexa = hexa.substring(1);
      }
      if (hexa.length === 3) {
        hexa = hexa.charAt(0) + hexa.charAt(0) +
               hexa.charAt(1) + hexa.charAt(1) +
               hexa.charAt(2) + hexa.charAt(2);
      }
      if (hexa.length !== 6) {
        rgb = "(Invalid, must be 3 or 6 characters.)";
      }
      else {
        rgb = [
          parseInt(hexa.substring(0,2), 16),
          parseInt(hexa.substring(2,4), 16),
          parseInt(hexa.substring(4,6), 16)
        ].join(' ');
      }
          
      hexa = prompt(hexa + ' converts to the RGB below.\n' +
                    'Enter another or Cancel to stop',
                    rgb);
    }

Leave a Reply