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

157
Visualizações
Changing hex color from string's color

So I've seen a bunch posted like this but none solved anything for me.


const HexPattern = /(#[0-9a-f]{6})(\s*[\w,]+\s*)/gi

function parseColors(str) {
  return str.replace(HexPattern, (s, g0, g1) => `<span style="color:${g0}">${g1}</span>`)
}

If I were to use this code it would replace the text after the hex color in the string with the color but I would want to change the actual hex color string into that color so like if my string was:

let string = "hello there #191919 <-- see that thats black"

it would change the #191919 into the hex color represented there and not the text after like my current code does which I found on stackoverflow.

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

0

The issue in your question is all in the regex. If you only want to replace the hex colour value in the string with that colour then the second matching group, (\s*[\w,]+\s*), can be removed.

That leaves you with this: /(#[0-9a-f]{6})/gi. However it's worth noting that a valid hex colour code can have 3, 6 or 8 characters, so you may also need to cater for that. The example below shows you how to do this:

const hexPattern = /(#[0-9a-f]{8}|#[0-9a-f]{6}|#[0-9a-f]{3})/gi
let parseColors = str => str.replace(hexPattern, (s, match) => `<span style="color:${match}">${match}</span>`);

$('div').html((i, t) => parseColors(t));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div>Some 3 character hex values: #C00 and #937</div>
<div>Some 6 character hex values: #545234 and #C8929A</div>
<div>Some 8 character hex values: #A63098FF and #00000066</div>

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