简体   繁体   中英

Regex for removing empty tags or with only spaces/tabs in it

Sorry for initial post, was sent to early... Here again:

Im looking for a regex in Javascript replacing the p-tag with empty or with any spaces or tabs filled in it by '', like:

<p></p>

or

<p>      </p>

If there are any other signs than space(s) and tab(s) between the tag then the complete tag with its content should be untouched (NOT replaced by '') like:

<p>    A  </p>

I have tried something like this but it doesn't work:

myString.replace( new RegExp( "<p>[\s]+</p>", "g" ), "" );

A quick google will show you a ton of posts explaining why regex and HTML do not mix. You can quite easily find empty elements and then do what you like with them by searching the DOM like normal.

var tags_i_want = document.querySelectorAll('p');

for(i = 0; i < tags_i_want.length; i++) {
    if(tags_i_want[i].innerHTML.trim() == '') {
        // Do whatever you need to
    }
}

Here is some JavaScript Voodoo Parts, for you to try:

 function delEmptyTags( x ) { var e = document.getElementsByTagName(x),a = [].slice.call(e), i; console.log( "paragraphs total: " + e.length ); while( a[0] ) i = a.pop(), !i.innerText ? i.outerHTML = '' : 0; console.log( "paragraphs left: " + e.length ); }; Execute: delEmptyTags( "p" );
 <p> P has text 1 <p> <!-- has empty spaces --> <p> <!-- has tabs --> <p> <!-- has new lines --> <p> P has text 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM