Search code examples
javascriptjqueryhtmlregexjquery-1.4

jQuery/JS, removing/trimming trailing html line breaks?


I'm looking for some ideas for the most efficient way to remove trailing html <br/> tags using javascript or jquery.

RULES:

  1. The br, at the front and end must be removed.
  2. It must remove non-closing and self-closing br tags.
  3. All br within the textual content must remain untouched.

THE HTML:

<div class="generatedContent">
    <br>My awesome content.
    <br><br>Some More awesome content.
    <br>
    <br>
    <br>I still need the content written here<br/>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
</div>



THE DESIRED OUTPUT:

<div class="generatedContent">
    My awesome content.
    <br><br>Some More awesome content.
    <br>
    <br>
    <br>I still need the content written here
</div>

Solution

  • Can't understand why you'd want to to use regular expressions for this, as most answers are. Using DOM methods is easy here:

    function isBrOrWhitespace(node) {
        return node && ( (node.nodeType == 1 && node.nodeName.toLowerCase() == "br") ||
               (node.nodeType == 3 && /^\s*$/.test(node.nodeValue) ) );
    }
    
    function trimBrs(node) {
        while ( isBrOrWhitespace(node.firstChild) ) {
            node.removeChild(node.firstChild);
        }
        while ( isBrOrWhitespace(node.lastChild) ) {
            node.removeChild(node.lastChild);
        }
    }
    
    $(".generatedContent").each( function() {
        trimBrs(this);
    } );