admin管理员组

文章数量:1404923

I have the following code to detect if there is content within a certain div:

if ($(".bio").html().length > 0) {
   $('.author-info').hide();
} 

The problem I run into is there are cases where a space may be in the .bio field. I want to check the length excluding spaces. In other words, check to see if the div has content but spaces do not count as content.

How do I do this?

Note: I am using jQuery 2.1.1.

I have the following code to detect if there is content within a certain div:

if ($(".bio").html().length > 0) {
   $('.author-info').hide();
} 

The problem I run into is there are cases where a space may be in the .bio field. I want to check the length excluding spaces. In other words, check to see if the div has content but spaces do not count as content.

How do I do this?

Note: I am using jQuery 2.1.1.

Share Improve this question asked Dec 8, 2014 at 22:21 L84L84 46.3k59 gold badges181 silver badges259 bronze badges 3
  • possible duplicate of character count using jquery – apaul Commented Dec 8, 2014 at 22:27
  • @apaul34208 - While I can gleam an answer from that question unsure if it is an exact duplicate. – L84 Commented Dec 8, 2014 at 22:29
  • Why the downvote? Please leave a ment if you downvote. – L84 Commented Dec 8, 2014 at 22:42
Add a ment  | 

4 Answers 4

Reset to default 5

You can remove all the spaces and check the length of the result:

$(".bio").text().replace(/ /g, '').length > 0

We could also be more general and select all whitespace with \s:

$(function(){
  $(".bio").each(function(){
    if( $(this).text().replace(/\s/g, '').length > 0 ){
      $(this).after("<- Has text");
    } else {
      $(this).after("<- Just spaces");
    }
  });
});
<script src="https://ajax.googleapis./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>

if($(".bio").html().trim().length > 0){
    ...
}

See .trim()

You could just add another condition to check if there is space like so:

if (($(".bio").html().length > 0)&&($(".bio").text()!=" ")) 
{
   $('.author-info').hide();
} 

As an alternative to @abl and @Purag's good answers, you can also manually loop through the text, looking for non-space characters:

var bioContent = $(".bio").html();
var hasContent = false;
var characterToIgnore = ' ';

for (var i=0;i<bioContent.length;i++){
    if (bioContent[i] != characterToIgnore){
        hasContent = true;
        break;
    }
}

JSFiddle

本文标签: javascriptCheck length of div excluding spacesStack Overflow