I know this is really basic, but I am new to javascript and can't find an answer anywhere.
How can I check if a string is empty?
I check length.
if (str.length == 0) {
}
if (!str || str.length === 0)
would be preferable. (Note the 3 equals signs.) +1 to @Dustin though.length
counts the blank spaces, so with length
we can't determine whether a string is empty or not.""
. OP is asking about empty string and I think this solution works well.===
is better in general, but for this specific case, I can't find a reason where str.length
would be zero due to type conversion. Are you using it as a convention or is there an example where you can get unexpected results?if (!str || str.trim().length === 0)
If you want to know if it's an empty string use === instead of ==.
if(variable === "") {
}
This is because === will only return true if the values on both sides are of the same type, in this case a string.
for example: (false == "") will return true, and (false === "") will return false.
But for a better check:
if(str === null || str === '')
{
//enter code here
}
if (!str)
. But if you're checking for empty string, as per the question, I think nxt's is the best. The accepted answer should be using ===, and if str is null/undefined, you get your classic Uncaught ReferenceError.str
is null
, while null
is an object
type, not string
.if (value == "") {
// it is empty
}
isBlank
which would bevariable.trim() === ''