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

203
Views
regex to replace "<p><br/></p>" string with empty string- Javascript

I have some HTML as a string

var str= "<p><br/></p>"

How do I strip the p tags from this string using JS. here is what I have tried so far:

str.replace(/<p[^>]*>(?:\s|&nbsp;)*<\/p>/, "") // o/p: <p><br></p>'
str.replace("/<p[^>]*><\\/p[^>]*>/", "")// o/p: <p><br></p>'
str.replace(/<p><br><\/p>/g, "")// o/p: <p><br></p>'

all of them return me same str as above, expected o/p is: str should be "" what im doing wrong here?

Thanks

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

0

You probably should not be using RegExp to parse HTML - it's not particularly useful with (X)HTML-style markup as there are way too many edge cases.

Instead, parse the HTML as you would an element in the DOM, then compare the trim()med innerText value of each <p> with a blank string, and remove those that are equal:

var str = "<p><br/></p><p>This paragraph has text</p>"
var ele = document.createElement('body');
ele.innerHTML = str;
[...ele.querySelectorAll('p')].forEach(para => {
  if (para.innerText.trim() === "") ele.removeChild(para);
});

console.log(ele.innerHTML);

about 4 years ago · Juan Pablo Isaza Report

0

You should be able to use the following expression: <p[^>]*>(&nbsp;|\s+|<br\s*\/?>)*<\/p>

The expression above looks at expressions enclosed in <p>...</p> and matches them against &nbsp;, whitespace (\s+) and <br> (and / variations).

I think you were mostly there with /<p[^>]*>(?:\s|&nbsp;)*<\/p>/, but you just needed to remove ?: (not sure what you were trying to do here), and adding an additional case for <br>.

const str = `
<p><br></p>
<p><br/></p>
<p><br /></p>
<p> <br/> </p>
<p> </p>
<p>&nbsp; </p>
<p><br/> &nbsp;</p>
<p>
  <br>
</p><!-- multiline -->
<p><br/> don't replace me</p>
<p>don't replace me</p>
`;

const exp = /<p[^>]*>(&nbsp;|\s+|<br\s*\/?>)*<\/p>/g;

console.log(str.replace(exp, ''));

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!