Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
function will work with a fixed value but not with the variable that produces it

I have this function:

function rgbtohex(val) {
  var clean = val.replace(/[^0-9\.,]/g, "");
  var colors = clean.split(',');
  var r = colors[0];
  var g = colors[1];
  var b = colors[2];

  return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

console.log(rgbtohex('rgb(64, 128, 128)')); //should output #408080, instead it outputs #1004288128

it's supposed to convert rgb to hex, something like this:

rgbtohex('rgb(64, 128, 128)') //should output #408080, instead it outputs #1004288128

but it outputs a wrong value. After breaking it down I found out it will work with the given value if var b equals a fixed value (in this case 128) instead of a variable. Like this:

 var r = colors[0];
 var g = colors[1];
 var b = 128;

why is that?

Fiddle here: https://jsfiddle.net/kr2bmaxp/2/

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your colors array is an array of strings, try converting it to numbers:

function rgbtohex(val) {
 var clean = val.replace(/[^0-9\.,]/g, "");
 var colors = clean.split(',').map(Number);
 var r = colors[0];
 var g = colors[1];
 var b = colors[2];
 
  return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
} 

console.log(rgbtohex('rgb(64, 128, 128)')) //should output #408080, instead it outputs #1004288128

Note that with destructuring syntax you can reduce the code a bit:

let [r, g, b] = clean.split(',').map(Number);
// delete the individual r, g, b assignments
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda