Creating strings

You can call any of the methods of the String class by using the new String() constructor method or by using a string literal value. If you specify a string literal, the ActionScript interpreter automatically converts it to a temporary String object, calls the method, and discards the temporary String object. You can also use the String.length property with a string literal.

Do not confuse a string literal with a String object. For more information on string literals and the String object, see About literals.

In the following example, the line of code creates the firstStr string literal. To declare a string literal, use single straight quotation mark (') or double straight quotation mark (") delimiters.

To create and use strings:

  1. Create a new Flash document and save it as strings.fla.
  2. Add the following ActionScript to Frame 1 of the main Timeline:
    var firstStr:String = "foo";
    var secondStr:String = new String("foo");
    trace(firstStr == secondStr); // true
    var thirdStr:String;
    trace(thirdStr); // undefined
    

    This code defines three String objects, one that uses a string literal, one that uses the new operator, and the other without an initial value. Strings can be compared by using the equality (==) operator, as shown in the third line of code. When referring to variables, you specify the data type only when the variable is being defined.

  3. Select Control > Test Movie to test the document.

Always use string literals unless you specifically need to use a String object. For more information on string literals and the String object, see About literals.

To use single straight quotation mark (') and double straight quotation mark (") delimiters within a single string literal, use the backslash character (\) to escape the character. The following two strings are equivalent:

var firstStr:String = "That's \"fine\"";
var secondStr:String = 'That\'s "fine"';

For more information on using the backslash character in strings, see About the escape character.

Remember that you cannot use "curly quotation mark" or "special quotation mark" characters within your ActionScript code; they are different from the straight quotation marks (') and (") that you can use in your code. When you paste text from another source into ActionScript, such as the web or a Word document, be sure to use straight quote delimiters.

For a sample source file, strings.fla, that shows you how to build a simple word processor that compares and retrieves string and substring selections, see the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download and decompress the Samples zip file and navigate to the ActionScript2.0/Strings folder to access the sample.