10

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
  • 5,832
  • 18
  • 55
  • 90

3 Answers3

33

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."

Richard Walton
  • 4,789
  • 3
  • 38
  • 49
  • Me too :S, It is emportant not to compare against "" so as not to create unnecessary strings – Hassan Mokdad Feb 18 '12 at 10:26
  • This works indeed. Look at the paragraph **casting to boolean** here http://help.adobe.com/en_US/as3/learn/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f9c.html#WS5b3ccc516d4fbf351e63e3d118a9b90204-7f87 – sch Feb 18 '12 at 10:42
  • Bellissimo! The most elegant solution :) – Learner Jul 28 '16 at 23:47
5

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)){
   ...
}
Subodh Joshi
  • 12,717
  • 29
  • 108
  • 202
Davem M
  • 477
  • 7
  • 9
4

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.

sch
  • 27,436
  • 3
  • 68
  • 83