O'Reilly logo

Actionscript Cookbook by Joey Lott

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

9.1. Joining Strings

Problem

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

Solution

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

Discussion

You can join together multiple strings in a single expression using the concatenation operator (+) between the two string operands:

// Results in a single value of "Thisworks" (no space)
myString = "This" + "works";

If you want to join together 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)
myString = "This" + " " + "works";

In the preceding examples, there is little reason why you would need to join together 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 together not only string literals, but also variables containing string values (or values that can be converted to strings). For example:

num = 24.
// Results in a single value of "There are 24 people"
myString = "There are " + num  + " people";

The concatenation operator automatically converts any non-string values to strings, as long as at least one of the operands in the statement is a string. In the preceding example, the number 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