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

217
Vistas
How to strip HTML from text using JavaScript but keep a space between each line?

I am using this answer to strip HTML from text.

This is how it works:

function strip(html){
   let doc = new DOMParser().parseFromString(html, 'text/html');
   return doc.body.textContent || "";
}

If I have some HTML like this:

This is the first line<br>
This is the second line<br>
This is the third line

It strips out the line breaks, and creates text like this:

This is the first lineThis is the second lineThis is the third line

But as you can see when it removes the line breaks there is no space left between each sentence. This is not how I want it to look.

How do I retain a space between each line (or sentence) after it strips the HTML?

I want it to look something like this:

This is the first line This is the second line This is the third line
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Yes, that's possible, but you'd have to manipulate the doc before geting the text content:

let doc = new DOMParser().parseFromString('This is the first line<br>\
This is the second line<br>\
This is the third line', 'text/html');

console.log(doc.body.textContent);

doc.body.querySelectorAll('br')                      // Get all <br> elements
  .forEach(br => br.after(doc.createTextNode(' '))); // And spaces after them 

console.log(doc.body.textContent);

I'm using querySelectorAll to get all linebreaks, and then I add a space text node after each one.

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