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

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

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 Relatório

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