Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

146
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda