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:
"Macromedia" + "Flash"
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:
"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 saw earlier because the empty string has ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access