Check if a string is empty in action script, similar to String.Empty in .net
16,850
Solution 1
You can simply do:
if(string)
{
// String isn't null and has a length > 0
}
else
{
// String is null or has a 0 length
}
This works because the string is coerced to a boolean value using these rules:
String -> Boolean = "false if the value is null or the empty string ( "" ); true otherwise."
Solution 2
The following will catch all of these:
- NULL
- empty string
- whitespace only string
import mx.utils.StringUtil;
var str:String
if(!StringUtil.trim(str)){
...
}
Solution 3
You can use length
but that is a normal property not a static one. You can find here all the properties of of the class String. If length is 0
the string is empty. So you can do your tests as follows if you want to distinguish between a null
String and an empty one:
if (!myString) {
// string is null
} else if (!myString.length) {
// string is empty
} else {
// string is not empty
}
Or you can use Richie_W's solution if you don't need to distinguish between empty and null strings.
![Hassan Mokdad](https://i.stack.imgur.com/fuYoX.jpg?s=256&g=1)
Author by
Hassan Mokdad
Updated on June 04, 2022Comments
-
Hassan Mokdad about 2 years
Is there a static property in Action similar to that in the String object in .net to check if a string is empty, that is String.Empty.
Thanks
-
Hassan Mokdad over 12 yearsMe too :S, It is emportant not to compare against "" so as not to create unnecessary strings
-
sch over 12 yearsThis works indeed. Look at the paragraph casting to boolean here help.adobe.com/en_US/as3/learn/…
-
Hassan Mokdad over 12 yearsThanks, actually I need only to check if empty or null
-
Learner almost 8 yearsBellissimo! The most elegant solution :)
-
Florian F over 4 yearsIt does not answer exactly the question, but is useful nonthelesss.