Remove duplicate <br /> tag from text node

I have a section of code that I am attempting to remove duplicate <br /> tags from. I understand that there are better ways to do this, but for the time being my only option is to do it client side with javascript/jquery (as I do not have control over the source html).

You can view the working example here to play around with it:

The text node looks like this:

<div class="show-tooltip-text">
<p><sup>2</sup>lots of text 
can be seen here.
<br><br>another lines text
<br><br>another lines text
<br><br>another lines text
<br><br>
<br><br>
<br><br>another lines text
<br><br>
<br><br>another lines text
<br><br>another lines text
<br><br>another lines text
<br><br>another lines text
<br><br>another lines text
<br><br>another lines text
<br><br>another lines text
<br><br>
<br><br>another lines text
<br><br>another lines text
<br><br>another lines text</p>
</div>

My Jquery looks like this:

$(function() {
  $("br + br",$(".show-tooltip-text")).each(function(){ 
  	if($(this).prev()[0].nodeName == this.nodeName){
        	$(this).remove()
        }
  });
});

I realize the problem is that prev doesn’t account for text as nodes. So when running prev on a single text node it only sees the <br> tags which results in it removing all but the very first <br>. My goal is to have it reduce every grouping of <br> tags down to 1 <br> tag. So I still want the spacing, I just want it to be a single space. It seems like the only way to do this might be a regex, but I’m not sure how to begin such a regex.

Thanks for your help.

This doesn’t use jquery, but you can fiddle it to select only the class you want:

document.body.innerHTML=document.body.innerHTML.replace(/(<br>\\s*){2,}/g,'<br>');

You could just check if the next element is a br element, and if so, remove it.


$('br').each(function () {
    if ($(this).next().is('br')) {
        $(this).next().remove();
    }
});

Thanks for the suggestions, this is the ultimate solution I went with:

$('.show-tooltip-text').each(function(){
			$(this).html($(this).html().replace(/(<br>\\s*){2,2}/g,'<br>'));
	});

Turns out if you want this to work in IE and want a better all around solution you should make the search case insensitive like this:


$('.show-tooltip-text').each(function(){
   $(this).html($(this).html().replace(/(<br>\\s*){2,2}/gi,'<br>'));
});

Even though my suggestion from earlier looks simpler, you may find that it does the better job, as well as being easier to understand too.


$('.show-tooltip-text br').each(function () {
    if ($(this).next().is('br')) {
        $(this).next().remove();
    }
});