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

225
Views
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 answers
Answer question

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 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!