
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Working with Strings
|
89
Joining Strings Together
Joining strings together (creating a new string from two or more strings) is called
concatenation. As we’ve seen, we can concatenate two strings with the plus operator
(
+), like this:
"Macromedia" + "Flash"
This line of code yields the single string value “MacromediaFlash”. Oops! We forgot
to put a space between the words. To add the space, we can insert it within the
quotes that define one of the strings, such as:
"Macromedia " + "Flash" // Yields "Macromedia Flash"
But that’s not always practical. In most cases, we don’t want to add a space to a
company or a product name. So instead, we join three strings together, the middle
one of which is simply an empty space:
"Macromedia" + " " + "Flash" // Also yields "Macromedia Flash"
Note that the space character is not the same as the empty string we discussed ear-
lier, because the empty string has no characters between the quotes.
Ordinarily, you wouldn’t concatenate literal strings, because you could more easily
write the result as one string—“Macromedia Flash”—in the first place. As a more
realistic example, we can concatenate variables that contain string data. Consider the
following code:
var company = "Macromedia";
var product = "Flash";
// Set the variable sectionTitle to "Macromedia Flash" ...