Strings
Explore how JavaScript uses strings to represent text values, learn to concatenate strings with the plus operator, and understand how to include special characters with escape sequences. This lesson helps you write and format text correctly in your code.
We'll cover the following...
Strings
Strings, another basic data type, represent a string (or sequence) of characters. Strings are how we represent text values in our code.
Strings can be created by wrapping text in single ('') or double ("") quotation marks.
String operations #
Operations on strings are limited. For instance, you cannot subtract, multiply, or divide a string with another string. You can, however, concatenate (combine) strings using the + operator.
Exercise
Using the concepts we have discussed for strings, create a sentence by concatenating all the strings given in the code. Store your results in a variable named sentence. You can use the strings more than once if needed.
Escaping characters
There are many string values that require escaped characters. Say you want to include a quote in quotation marks. Do you think the following code will run correctly? If you run the following code, you’ll see that the system throws an error.
This is because the " is a reserved character that indicates the start and end of a string. In the above code, we have two empty strings and a bunch of stuff in the middle that the program doesn’t recognize.
In order to indicate that we want to use the " as a quotation mark, we have to escape the character using a backslash (\).
Let’s break down this example:
- The first
"indicates the start of the string. - The escaped characters (
\") are used to include quotation marks in the string. - The last
"indicates the end of the string.
There are a few different characters that you must escape in order for the program to interpret a string in the correct way. These include:
- A single quote:
\' - A double quote:
\" - A backslash:
\\
Escaped characters can also be used to add tabs or go to the next line in your strings, with the following:
- A new line:
\n - A tab:
\t
Exercise #
Create a string variable with two sentences (named twosentences) and separate the sentences by a new line (\n).