How can I check for an empty/undefined/null string in JavaScript?
How can I check for an empty/undefined/null string in JavaScript?
Question
I saw this question, 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 ""
?
Accepted Answer
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).
if (strValue === "") {
//...
}
Read more… Read less…
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 previous answers are good, but this will be even better. Use the !!
(not not) operator.
if(!!str){
// Some code here
}
Or use type casting:
if(Boolean(str)){
// Code here
}
Both do the same function. Typecast the variable to Boolean, where str
is a variable.
It returns false
for null,undefined,0,000,"",false
.
It returns true
for string "0" and whitespace " ".
The closest thing you can get to str.Empty
(with the precondition that str is a String) is:
if (!str.length) { ...
If you need to make sure that the string is not just a bunch of empty spaces (I'm assuming this is for form validation) you need to do a replace on the spaces.
if(str.replace(/\s/g,"") == ""){
}
I use:
function empty(e) {
switch (e) {
case "":
case 0:
case "0":
case null:
case false:
case typeof(e) == "undefined":
return true;
default:
return false;
}
}
empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
return ""
})) // false