Search code examples
javascriptjqueryhtmlreplaceline-breaks

Replace multiple <br>'s with only one <br>


How do I use JavaScript to detect

<br>
<br>
<br>

to become one

<br>

?

I tried with:

jQuery('body').html().replace(/(\<br\>\r\n){3, }/g,"\n");

but this is not working for me.


Solution

  • Simpler:

    var newText = oldText.replace(/(<br\s*\/?>){3,}/gi, '<br>');

    This will allow optional tag terminator (/>) and also spaces before tag end (e.g. <br /> or <br >).