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

328
Vistas
Simple JS code for highlighting search text in a paragraph

I am trying to rewrite this code to suit my needs, but I am lost in all the replacing magic that the auther of the Fiddle does. Here's my modified fiddle.

My goal is to find all occurrances of "a" letter in the paragraph and highlight them. I just can't figure out why my letters are just being replaced by 1$ instead of being highlighted. Can anyone help me with this ?

HTML

<div id="searchtext">
  <p>I want to highlight all "a" letters in this paragraph</p>
</div>

JS

$(document).ready(function() {
      var text = 'a';
      var query = new RegExp(text, "gim");
      var e = document.getElementById("searchtext").innerHTML;
      var enew = e.replace(/(<span>|<\/span>)/igm, "");
      document.getElementById("searchtext").innerHTML = enew;
      var newe = enew.replace(query, "<span>1$</span>");
      document.getElementById("searchtext").innerHTML = newe;
    });

CSS:

#searchtext span {
  background-color: #FF9;
  color: #555;
}
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Use \$& instead

$(document).ready(function() {
      var text = 'a';
      var query = new RegExp(text, "gim");
      var e = document.getElementById("searchtext").innerHTML;
      var enew = e.replace(/(<span>|<\/span>)/igm, "");
      document.getElementById("searchtext").innerHTML = enew;
      var newe = enew.replace(query, "<span>\$&</span>");
      document.getElementById("searchtext").innerHTML = newe;
    });
#searchtext span {
  background-color: #FF9;
  color: #555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="searchtext">
  <p>I want to highlight all "a" letters in this paragraph</p>
</div>

More information about $&

about 4 years ago · Santiago Trujillo 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