Escape Sequences in Strings:
Quotes are not the only characters that can be escaped inside a string. There are two reasons to use escaping characters:
To allow you to use characters you may not otherwise be able to type out, such as a carriage return.
To allow you to represent multiple quotes in a string without JavaScript misinterpreting what you mean.
Code Output
\' single quote
\" double quote
\\ backslash
\n newline
\r carriage return
\t tab
\b word boundary
\f form feed
Note that the backslash itself must be escaped in order to display it as a backslash.
Concatenating Strings with Plus Operator:
In JavaScript, when the + operator is used with a String value, it is called the concatenation operator. You can build a new string out of other strings by concatenating them together.
Example:
'My name is Alan,' + ' I concatenate.'
Note: Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
Example:
const ourStr = "I come first. " + "I come second.";
The string I come first. I come second. would be displayed in the console.
Concatenating Strings with the Plus Equals Operator:
We can also use the += operator to concatenate a string onto the end of an existing string variable. This can be very helpful to break a long string over several lines.
Note: Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
Example:
let ourStr = "I come first. ";
ourStr += "I come second.";
ourStr now has a value of the string I come first. I come second.
Constructing Strings with Variables:
Sometimes you will need to build a string, Mad Libs style. By using the concatenation operator (+), you can insert one or more variables into a string you're building.
Example:
const ourName = "freeCodeCamp";
const ourStr = "Hello, our name is " + ourName + ", how are you?";
ourStr would have a value of the string Hello, our name is freeCodeCamp, how are you?.
Appending Variables to Strings:
Just as we can build a string over multiple lines out of string literals, we can also append variables to a string using the plus equals (+=) operator.
Example:
const anAdjective = "awesome!";
let ourStr = "freeCodeCamp is ";
ourStr += anAdjective;
ourStr would have the value freeCodeCamp is awesome!.
No comments:
Post a Comment