Strings
String Variables¶
We have to process lots of strings (characters) in programs a lot too. So variables will often contain strings.
Strings are a series of characters surrounded by double or single quotes.
"This is a string" "This isn't a number" "99" 'This is a string too' 'The cow says, "moo"' "Fred" "Bert" "Ernie"
You have to have quotes around a string.
- If a string is surrounded by double quotes then you can have single quotes inside the string.
- If a string is surrounded by single quotes then you can have double quotes inside the string.
- That's clever!
- But, sometimes we need to put a character into a string that is special, like a tab. How do we do that?
Escape Characters¶
Here's a list of characters that we need to be able to embed into strings.
To embed them in a string you just type the code with the backslash.
Code | Special Character |
---|---|
\t | Tab |
\n | New Line |
\\ | Literal backslash |
\" | Double Quote |
\' | Single Quote |
Example of an escaping character¶
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Single Quote Example¶
1 2 3 4 5 6 7 8 |
|
Double Quote Example¶
1 2 3 4 5 6 7 8 |
|
Single and Double Quote Example¶
1 2 3 4 5 6 7 8 |
|
Tab Example¶
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
The .length
Property¶
- There are lots of methods in JavaScript that let us manipulate strings. However, one of the most famous things associated with strings is not a method, but rather a "property." (A "property" is just object-oriented talk for a characteristic of an object.) Here is a famous property of a string.
- Length of a string: You use the "
.length
" property
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Line Continuation¶
When you have JavaScript statement that exceed more than one line, you can concatenate them together.
1 2 3 4 5 6 |
|
Here's an example using variables. Variables do not have quotes around them, so you have to concatenate each variable with a string.
1 2 3 4 5 6 7 |
|
Coding Standard
If a line of code is too long to fit on one line of the text editor (see Line Length standard below), the continuation of the line must be indented in by eight (8) spaces to visually emphasize that this line is a continuation.
Read more¶
Related Reading
Pages 161 - 166 — Same as numbers, this jumps ahead pretty quickly. Read on if you'd like, but know we'll talk more about strings in Unit 2.
Hands on work¶
Demo
- String Variables
- unit01/demos/demo-strings.html
Labs
- String Variables
- unit01/labs/lab-06-stringVariables.html
Exercises
- Lab06 exercise
- unit01/exercises/exercise-06.html