Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
Encuentre texto y reemplácelo con una imagen en Jquery para múltiples instancias de texto

Tengo varios fragmentos de texto que necesitan reemplazo en una página para las imágenes correspondientes.

tengo este codigo:

 $('.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="" />')); });

Desafortunadamente, solo reemplaza 1 de los 3. ¿Cómo hago para que actualice los 3?

Gracias

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Desea actualizar el text con cada reemplazo, luego llame a .html() con text , que luego tiene todos los reemplazos:

 $('.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 Report

0

Mira este violín: 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 Report

0

Suponiendo que el texto que se va a reemplazar siempre es un número entero y siempre coincide con el nombre de archivo de la imagen, puede hacer que el código sea de una sola línea usando una función de flecha y una expresión regular:

 $('.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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!