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

233
Views
¿Cómo implementar la función .each() en un fragmento de código?

Todavía estoy tratando de aprender los conceptos básicos de JS.

Básicamente, solo quiero eliminar la primera palabra de una clase determinada. Como esto:

antes :

 <span class="remove-word">on the beach</span>

Después:

 <span class="remove-word">the beach</span>

Me las arreglé para hacerlo mediante la creación de este fragmento de código:

 jQuery(document).ready( function(){ jQuery('.remove-word').text(jQuery('.remove-word').text().replace('on','')); jQuery('.remove-word').text(jQuery('.remove-word').text().replace('at','')); });

El problema ahora es que esto funciona bien si solo tengo una instancia de la clase ".remove-word" presente en una página, pero como tengo muchas, necesito envolver el código en una función .each(), de lo contrario sucede esto:

 jQuery(document).ready( function(){ jQuery('.remove-word').text(jQuery('.remove-word').text().replace('on','')); jQuery('.remove-word').text(jQuery('.remove-word').text().replace('at','')); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div><span class="remove-word">on the beach</span></div> <div><span class="remove-word">at the roof</span></div> <div><span class="remove-word">on the hill</span></div>

¿Cómo implemento la función .each() aquí?

Alternativamente, creo que un script que simplemente elimine la primera palabra sin buscar "on" o "at" sería ideal, pero lo intenté y está fuera de mi alcance con mi conocimiento limitado de js tal como están las cosas, por eso lo hice. en su lugar, usando la forma .replace().

Gracias.

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

0

¿Qué pasa con esto?

 jQuery('.remove-word').each(function( index ) { //get the index of the first space to the end of the string var firstWord = $(this).text().substring($(this).text().indexOf(' '), $(this).text().length); //set the value $(this).text(firstWord ); });

Querrá hacer un manejo de errores para .remove-word donde no hay texto o espacios, pero este debería ser un buen punto de partida.

about 4 years ago · Juan Pablo Isaza Report

0

Puedes hacerlo. Puede agregar .each a la clase .remove-word y luego reemplazar su contenido.

 $(document).ready(function() { $(".remove-word").each((idx,htmlSpan)=>{ $(htmlSpan).text($(htmlSpan).text().replace('at','')); }) });

Si solo desea eliminar solo la primera palabra, puede hacerlo.

 $(document).ready(function() { $(".remove-word").each((idx,htmlSpan)=>{ let text = $(htmlSpan).text(); // get text let splittedText = text.split(" "); // split sentence on space. returns array. let remainingWords = splittedText.splice(1); // get array from index 1 to last so index 0 is removed. $(htmlSpan).text(remainingWords.join(" ")) // .join is joining string with " " space }) });
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!