O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Joining Strings

Problem

You want to concatenate (join) together two or more strings into a single value.

Solution

Use the string concatenation operator +, the combination concatenation-assignment operator +=, or the String.concat() method.

Discussion

Multiple strings can be joined in a single expression using the concatenation operator, +, between two string operands:

// This results in a single value of "Thisworks" (no space)
var example:String = "This" + "works";

If you want to join more than two strings, use additional concatenation operators and string value operands in the appropriate order:

// Results in a single value of "This works" (with a space)
var example:String = "This" + " " + "works";

In the preceding examples, there is little reason why you would need to join the string literals instead of assigning a single string value ("This works" instead of "This" + " " + "works"). However, this demonstrates the technique you’ll use when working with dynamic values. You can use the concatenation operator to join not only string literals, but also variables containing string values (or values that can be converted to strings). For example:

var attendance:int = 24;
// Results in a single value of "There are 24 people"
var output:String = "There are " + attendance + " people";

The concatenation operator automatically converts any nonstring values to strings, as long as at least one of the operands in the statement is a string. In the preceding example, the numerical value 24 is converted ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required