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.
¿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.
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 }) });