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
4 Answers
Reset to default 5You 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"> </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
版权声明:本文标题:javascript - Check length of div excluding spaces - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744877006a2629974.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论