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

190
Views
Extraer la primera ocurrencia de una cadena

Tengo un div con un atributo contentEditable y me cuesta extraer la primera aparición de texto de una cadena.

Estoy usando innerHTML para obtener el texto (necesito usarlo, no puedo usar innerText o textContent ) y viene con mucho <br> .

La cadena será algo como esto:

' <br> Esto es algo de texto <br> <br> Otra pieza de texto'. Solo necesito el texto (' This is some text ') sin <br> .

La cadena siempre tendrá <br> y el lugar de <br> puede variar.

Intenté usar replaceAll('<br>', '') y devuelve 'This is some text Another piece of text' pero solo necesito la primera ocurrencia 'This is some text' .

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

0

Puede usar string.split() para dividir el contenido por <br> , luego ejecutarlo a través de un filtro simple que eliminará cualquier elemento vacío en la matriz y finalmente elegir el primer elemento de la matriz, que será el texto usted quiere.

 let fragment = document.querySelector('div.content').innerHTML.split('<br>').filter(a => a.trim())[0].trim() ; console.log(fragment);
 <div class='content'> <br> <br> <br> This is some text <br> <br> <br> This is some more text <br> </div>

about 4 years ago · Juan Pablo Isaza Report

0

Probar

 function getFirstNonBlankSubstring(text, separator) { const array = text.split(separator); for (const substring of array) { if (substring.trim()) { return substring; } } }

getFirstNonBlankSubstring(element.innerHTML, '<br>') debería brindarle lo que necesita siempre que pueda contar con las etiquetas <br> que se ven exactamente así.

Si no puede, es posible que deba recorrer el DOM para encontrar nodos de texto.

about 4 years ago · Juan Pablo Isaza Report

0

Puedes hacerlo así

 //get the text and remove white space from left var readText = document.getElementById("content").textContent.trimLeft(); //How many splits you want out var freeSpaces = 3; // var splittext = readText.split(' '); var newText = splittext.slice(0, freeSpaces); //final text var finalText = newText.join(' ');
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!