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:

  1. NULL
  2. empty string
  3. 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.

Share:
16,850
Hassan Mokdad
Author by

Hassan Mokdad

Updated on June 04, 2022

Comments

  • Hassan Mokdad
    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
    Hassan Mokdad over 12 years
    Me too :S, It is emportant not to compare against "" so as not to create unnecessary strings
  • sch
    sch over 12 years
    This works indeed. Look at the paragraph casting to boolean here help.adobe.com/en_US/as3/learn/…
  • Hassan Mokdad
    Hassan Mokdad over 12 years
    Thanks, actually I need only to check if empty or null
  • Learner
    Learner almost 8 years
    Bellissimo! The most elegant solution :)
  • Florian F
    Florian F over 4 years
    It does not answer exactly the question, but is useful nonthelesss.