Hex to RGB 2 (v5)

Revision 5 of this benchmark created on


Setup

function hextoRgb(hex) {
  if (/^#/i.test(hex)) {
    hex = hex.replace('#', '');
  }
  
  if (hex.length === 3) {
    const rHex = hex.substring(0,1);
    const gHex = hex.substring(1, 2);
    const bHex = hex.substring(2, 3);
    
    hex = `${rHex}${rHex}${gHex}${gHex}${bHex}${bHex}`;
  }
  
  const rDec = parseInt(hex.substring(0, 2), 16);
  const gDec = parseInt(hex.substring(2, 4), 16);
  const bDec = parseInt(hex.substring(4, 6), 16);
  
  return `rgb(${rDec},${gDec},${bDec})`;
}


function hextoRgb2(hex) {
  if (hex[0] === '#') {
    hex = hex.slice(1);
  }
  
  if (hex.length === 3) {
    const rHex = hex.substring(0,1);
    const gHex = hex.substring(1, 2);
    const bHex = hex.substring(2, 3);
    
    hex = `${rHex}${rHex}${gHex}${gHex}${bHex}${bHex}`;
  }
  
  const rDec = parseInt(hex.substring(0, 2), 16);
  const gDec = parseInt(hex.substring(2, 4), 16);
  const bDec = parseInt(hex.substring(4, 6), 16);
  
  return `rgb(${rDec},${gDec},${bDec})`;
}

Test runner

Ready to run.

Testing in
TestOps/sec
Not optimized
hextoRgb("#123");
hextoRgb("#123123");
ready
Optimized
hextoRgb2("#123");
hextoRgb2("#123123");
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.