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

user610983 picture user610983 · Jun 12, 2013 · Viewed 13k times · Source

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.

Answer

user1823761 picture user1823761 · Jun 12, 2013

CSS Solution

If you want to disable the effect of multiple <br> on the page, you can do it by CSS without using JavaScript:

br + br { display: none; }

However, this method is ideal when you are working with tags, something like this:

<div>Text</div><br /><br /><br />
<div>Text</div><br /><br /><br />
<div>Text</div><br /><br /><br />

In other cases, like this:

Hello World<br />   <br />
Hello World<br />   <br />
Hello World<br />   <br />

It will fail (as CSS passes text nodes). Instead, use a JavaScript solution.


JavaScript Solution

// It's better to wait for document ready instead of window.onload().
window.onload = function () {
    // Get all `br` tags, defined needed variables
    var br = document.getElementsByTagName('br'),
        l = br.length,
        i = 0,
        nextelem, elemname, include;
        
    // Loop through tags
    for (i; i < l - 1; i++) {
        // This flag indentify we should hide the next element or not
        include = false;
        
        // Getting next element
        nextelem = br[i].nextSibling;
        
        // Getting element name
        elemname = nextelem.nodeName.toLowerCase();
        
        // If element name is `br`, set the flag as true.
        if (elemname == 'br') {
            include = true;
        }
        
        // If element name is `#text`, we face text node
        else if (elemname == '#text') {
            // If text node is only white space, we must pass it.
            // This is because of something like this: `<br />   <br />`
            if (! nextelem.data.replace(/\s+/g, '').length) {
                nextelem = br[i+1];
                include = true;
            }
        }
        
        // If the element is flagged as true, hide it
        if (include) {
            nextelem.style.display = 'none';
        }
    }
};