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

JavascriptJqueryHtmlReplaceLine Breaks

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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';
        }
    }
};

Solution 2 - Javascript

What is the point of sending HTML, which is in a form that you don't want, to the client browser and making it run JavaScript code to clean it up? This looks like a bad design.

How about fixing all your static HTML, and HTML generation, so that these superfluous <br> elements do not occur in the first place?

If you use JavaScript to modify the document object, do so for dynamic effects that cannot be achieved in any other way.

Solution 3 - Javascript

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 >).

Solution 4 - Javascript

Wouldn't something like this be the right approach:

$("br~br").remove()

EDIT: No, it's wrong, because its definition of "contiguous" is too loose, as per BoltClock.

Solution 5 - Javascript

This solution is jQuery + DOM only, does not manipulate HTML as string, works with text nodes, ignores whitespace only text nodes:

$('br').each(function () {
  const {nodeName} = this;

  let node = this;
  
  while (node = node.previousSibling) {
    if (node.nodeType !== Node.TEXT_NODE || node.nodeValue.trim() !== '') {
      break;
    };
  }
    
  if (node && node !== this && node.nodeName === nodeName) {
    $(node).remove();
  }
});

See: https://jsfiddle.net/kov35jct/

Solution 6 - Javascript

Try this

$('body').html($('body').html().replace(/(<br>)+/g,"<br>"));

It will replace n number of <br> into one.

Demo

Solution 7 - Javascript

I would go with this:

$('body').html($('body').html().replace(/<br\W?\\?>(\W?(<br\W?\\?>)+)+/g,"<br>"));

However, after reading the comments in another post here I do consider that you should try to avoid doing this in case you can correct it in the back end.

Solution 8 - Javascript

A lot of the other answers to this question will only replace up to certain amount of elements, or use complex loops. I came up with a simple regex that can be used to replace any number of <br> tags with a single tag. This works with multiple instances of multiple tags in a string.

/(<br>*)+/g

To implement this in JavaScript, you can use the String.replace method:

myString.replace(/(<br>*)+/g, "<br/>");

To replace multiple <br/> tags, add a / to the regex:

/(<br\/>*)+/g

Solution 9 - Javascript

Try this:

jQuery('body').html(
      jQuery('body').html().replace(/(?:<br>\s+){3,}/ig,"\n"));
);

DEMO: jsfiddle

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser610983View Question on Stackoverflow
Solution 1 - Javascriptuser1823761View Answer on Stackoverflow
Solution 2 - JavascriptKazView Answer on Stackoverflow
Solution 3 - JavascriptmarekfulView Answer on Stackoverflow
Solution 4 - JavascriptSteve BennettView Answer on Stackoverflow
Solution 5 - JavascriptP.P. KosztaView Answer on Stackoverflow
Solution 6 - JavascriptAmitView Answer on Stackoverflow
Solution 7 - JavascriptJair ReinaView Answer on Stackoverflow
Solution 8 - JavascriptBlake StevensonView Answer on Stackoverflow
Solution 9 - JavascriptStephanView Answer on Stackoverflow