Working with Strings
By manipulating strings we can program anything from a user-input validator to a word-scramble game. With a little ingenuity, we can make neat visual text effects and other fun stuff.
We can manipulate strings with both operators and built-in functions. String operators can join multiple strings together or compare the characters of two strings. Built-in functions can examine a string’s properties and contents, extract a portion of a string, check a character’s code point, create a character from a code point, change the case of the characters in a string, and even turn a string into a variable or property name.
Joining Strings Together
Joining strings together (creating a new string from two or more strings) is called concatenation. As seen earlier, we can concatenate two strings with the plus operator (+), like this:
That 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:
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:
Note that the space character is not the same as the empty string we saw earlier because the empty string has no characters between the quotes.
We can also concatenate variables that contain string data. Consider the following code:
In lines 1 and 2, we store string values in variables. Then, we join those values together with a space. Two of our string values are contained in variables, one (the space) is a string literal. Not a problem. Happens all the time.
Occasionally, we’ll want to append characters onto an existing string. For example, we could change the tone of a welcome message like this:
The preceding code gets the job done, but notice that we have to refer to greeting
twice in line 2. To be more efficient, we can use the += operator, which appends the string on its right to the string variable on the left:
Comments
Post a Comment