Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

218
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda