Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 247
Andrew Avatar asked Dec 05 '25 10:12

Andrew


2 Answers

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);
} );
like image 122
Tim Down Avatar answered Dec 07 '25 02:12

Tim Down


Try this:

var everything = $('.generatedContent').contents();
for(var i=everything.length-1;i>0;i--)
{
    if((everything.get(i).tagName == 'BR'
           && everything.get(i-1).tagName == 'BR')
        || (everything.get(i).textContent.match(/\w/)==null))
        $(everything.get(i)).remove();
    else
        break;
}

It seems to work in FF and IE7, that I've tried.

like image 36
Karl B Avatar answered Dec 07 '25 02:12

Karl B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!