troubleshooting Question

JavaScript/jQuery/REGEX: Replace multiple <br> tags with exactly two <br> tags

Avatar of hankknight
hankknightFlag for Canada asked on
JavaScriptRegular Expressions
8 Comments2 Solutions2076 ViewsLast Modified:
Using JavaScript / jQuery and REGEX, how can I replace all sets of more than two <br> tags with exactly two <br /> tags?

<br /><br><br /><br/><br>
Should become
<br /><br />

Please test your solution with the code below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">

<script type="text/javascript" src=""></script>
<script type="text/javascript">

$(document).ready(function() {
 $('div').each(function() {
  $(this).html( fixBR($(this).html()) );

function fixBR (str) {
 return str;


 Hello World.<br><br /><br /><br /><br /><br/>
 This is a test.<br /><br /><br /><br />Testing<br>
 <br /><br/>There should be a maximum of two br tags beteween each line of text.

 1234567890<br><br /><br /><br /><br /><br/>
 This is a test.<br /><br /><br /><br />Testing<br>


Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 2 Answers and 8 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 8 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros