检查div的长度,不包括空格

L84*_*L84 0 javascript jquery

我有以下代码来检测某个div中是否有内容:

if ($(".bio").html().length > 0) {
   $('.author-info').hide();
} 
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是有些空间可能在.bio现场.我想检查不包括空格的长度.换句话说,检查div是否包含内容但空格不计为内容.

我该怎么做呢?

注意:我使用的是jQuery 2.1.1.

Pur*_*rag 5

您可以删除所有空格并检查结果的长度:

$(".bio").text().replace(/ /g, '').length > 0
Run Code Online (Sandbox Code Playgroud)

我们也可以更通用,并选择所有空格\s:

$(function(){
  $(".bio").each(function(){
    if( $(this).text().replace(/\s/g, '').length > 0 ){
      $(this).after("<- Has text");
    } else {
      $(this).after("<- Just spaces");
    }
  });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="bio">Text with spaces</span>
<br>
<span class="bio">&nbsp;&nbsp; &nbsp;</span>
Run Code Online (Sandbox Code Playgroud)