1

I would like to remove any <br> tag which comes up just before a closing </p> tag.

For example this is ok :

<p>Bla bla bla <br>
bla bla
</p>

But this is NOT ok :

<p>Bla bla bla <br>
</p>

In other words, every time I have :

<br> + white space or tab or new line or whatever providing no content + </p> 

Then, I want to remove that <br>.

How would this be achieved with javascript Regex ? (or any other javascript way)

lapin
  • 2,098
  • 2
  • 21
  • 30

3 Answers3

1

You could do something like below. If the br is the last child remove it, else of the last child is empty then remove it

$('p').find('br:last').filter(function () {
  return !this.nextSibling || (this.nextSibling.nodeType == 3 && !this.nextSibling.nextSibling && !this.nextSibling.nodeValue.trim())
}).remove()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Bla bla bla
  <br/>bla bla
</p>

<p>Bla bla bla
  <br></p>

<p>Bla bla bla
  <br>
</p>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

Try this one:

Iterate through each p,
get its html (not text, in order to get the <br> element),
replace the <br> with empty string using regex (one that matches <br> just before the </p>),
replace the original with the updated html.

$('p').each(function(){
    var p = $(this);

    p.html(p.html().replace(/(<br)\s?\/?>\s?$/g,''));    

});

REGEX:
/(<br)\s?\/?>\s?$/g matches: <br>, <br/>, <br />, <br >

qtgye
  • 3,580
  • 2
  • 15
  • 30
0

The regexp would look like so:

/<br>\s*<\/p>/g

Meaning first a "<br>" + Any white space or newline + "</p>"

Then we use str.match(). And to remove the <br> we replace it with an empty string. Notice that test1 didn't work while test2 did:

var test1 = "<p>Bla bla bla <br> \
bla bla \
</p>";

var test2 = "<p>Bla bla bla <br> \
</p>";

if(test1.match(/<br>\s*<\/p>/g))
    test1 = test1.replace("<br>","");

if(test2.match(/<br>\s*<\/p>/g))
    test2 = test2.replace("<br>","");

alert(test1); // <br> still there
alert(test2);// <br> is gone
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
  • 1
    Thank you for your answer. It looks like it works great. I chose the other answer because it happened to be closer to the way I wanted to implement it. Thank you again. – lapin Feb 06 '15 at 06:13