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 f
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 === "") {
//...
}
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 didn't see a good answer here (at least not an answer that fits for me)
So I decided to answer myself:
value === undefined || value === null || value === "";
You need to start checking if it's undefined. Otherwise your method can explode, and then you can check if it equals null or is equal to an empty string.
You cannot have !! or only if(value)
since if you check 0
it's going to give you a false answer (0 is false).
With that said, wrap it up in a method like:
public static isEmpty(value: any): boolean {
return value === undefined || value === null || value === "";
}
PS.: You don't need to check typeof, since it would explode and throw even before it enters the method
Try this
str.value.length == 0
All the previous answers are good, but this will be even better. Use dual NOT operators (!!
):
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 " "
.
I usually use something like this,
if (!str.length) {
// Do something
}