简体   繁体   English

用于删除空标签或仅包含空格/制表符的正则表达式

[英]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:我在 Javascript 中寻找正则表达式,用空或任何空格或制表符替换 p-tag 用 '' 填充,例如:

<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.一个快速的谷歌会向你展示大量解释为什么正则表达式和 HTML 不混合的帖子。 You can quite easily find empty elements and then do what you like with them by searching the DOM like normal.你可以很容易地找到空元素,然后通过像往常一样搜索 DOM 来做你喜欢的事情。

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:这是一些 JavaScript Voodoo 部分,供您尝试:

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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