简体   繁体   English

JavaScript-检查html字符串是否只有空标签或

[英]JavaScript - check if string of html has only empty tags or  

I'm mapping an event calendar and one of the json nodes is an artist bio. 我正在映射事件日历,并且json节点之一是歌手简历。

For the bio node I'll get something like this and append it to the bio div. 对于bio节点,我将得到类似的内容并将其附加到bio div。

<p>John Doe was born in Nantucket..</p>
<p>Yada yada</p>

However, sometimes I get something like this and I want to set it to null so it doesn't print: 但是,有时我会收到类似的信息,但我想将其设置为null,这样它就不会打印:

<p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p>

How can I check the string for empty tags and / or &nbsp; 如何检查字符串中的空标签和/或&nbsp; specifically, ie 具体来说,即

if(event.bio //has only empty tags || only white space || '&nbsp;') { 
     bio = null; 
}

You could do something like: 您可以执行以下操作:

const aux = document.createElement('div');
aux.innerHTML = yourString; //parses the html
const trimmedContent = aux.innerText.trim(); //get only the text and remove white space at the beginning and end

Then you can check if trimmedContent == '' to know if it's empty. 然后,您可以检查trimmedContent == ''是否为空。

Try 尝试

let content = "<p>&nbsp;</p><p>&nbsp; </p><p>&nbsp; </p>"

content = content = content.replace(/(<\/?[^>]+(>|$)|&nbsp;|\s)/g, ""); 

if (content === "") bio = null

For clarity, 为了清楚起见,

 content = content = content.replace(/(<\/?[^>]+(>|$)|&nbsp;|\s)/g, "");

is a concise form of: 是以下内容的简洁形式:

content = content.replace(/<\/?[^>]+(>|$)/g, ""); //&nbsp;&nbsp; &nbsp;
content = content.replace(/&nbsp;/g, ""); //a space char
content = content.replace(/\s/g, ""); //empty string

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

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