How do you check for an empty string in JavaScript?
I saw this thread, but I didn't see a JavaScript specific example. Is there a simple string.Empty
available in JavaScript, or is it just a case of checking for ""
?
If you just want to check whether there's any value, you can do
if (strValue) {
//do something
}
If you need to check specifically for an empty string over null, I would think checking against ""
is your best bet, using the ===
operator (so that you know that it is, in fact, a string you're comparing against).
For checking if a string is empty, null or undefined I use:
function isEmpty(str) {
return (!str || 0 === str.length);
}
For checking if a string is blank, null or undefined I use:
function isBlank(str) {
return (!str || /^s*$/.test(str));
}
For checking if a string is blank or contains only white-space:
String.prototype.isEmpty = function() {
return (this.length === 0 || !this.trim());
};
All the above are good but this will be even better. use !!
(not not) operator.
if(!!str){
some code here;
}
or use type casting:
if(Boolean(str)){
codes here;
}
Both do the same function, type cast the variable to boolean, where str
is a variable.
Returns false
for null,undefined,0,000,"",false
.
Returns true
for string "0" and whitespace " ".
上一篇: .prop()vs .attr()