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

158
Vistas
Find text and replace with image in Jquery for multiple text instances

I have multiple pieces of text that need replacement on a page to corresponding images.

I have this code:

$('.icon-box-1').each(function() {
var text = $(this).text();
$(this).html(text.replace('1', '<img  src="1.png"  alt=""  />'));
$(this).html(text.replace('2', '<img  src="2.png"  alt=""  />'));
$(this).html(text.replace('3', '<img  src="3.png"  alt=""  />'));
});

Unfortunately it only replaces 1 of the 3. How do i get it to update all 3?

Thanks

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You want to update text with each replacement, then call .html() with text, which then has all of the replacements:

$('.icon-box-1').each(function() {
  var text = $(this).text()
    .replace('1', '<img  src="1.png"  alt=""  />')
    .replace('2', '<img  src="2.png"  alt=""  />')
    .replace('3', '<img  src="3.png"  alt=""  />');

  $(this).html(text);
});
about 4 years ago · Juan Pablo Isaza Denunciar

0

Check this fiddle: https://jsfiddle.net/qp78rdzo/

$('.icon-box-1').each(function() {
    var text = $(this).text();

    text = text.replace('1', '<img  src="1.png"  alt="">');
    text = text.replace('2', '<img  src="2.png"  alt="">');
    text = text.replace('3', '<img  src="3.png"  alt="">');

    $(this).html(text);
});
about 4 years ago · Juan Pablo Isaza Denunciar

0

Assuming that the text to be replaced is always an integer and always matches the filename of the image, then you can make the code a one-liner using an arrow function and a regular expression:

$('.icon-box-1').html((_, h) => h.replace(/(\d)/g, '<img src="$1.png" alt="$1" />'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="icon-box-1">This is 1</div>
<div class="icon-box-1">This is 2</div>
<div class="icon-box-1">This is 3</div>
<div class="icon-box-1">This is 1 and 2</div>
<div class="icon-box-1">This is 2 and 3</div>
<div class="icon-box-1">This is 3 and 1</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