Lesson 32 of 296
Strings and template literals
What you will learn
- Three ways to write a string
- Length and positions of characters
- Joining strings
- Template literals
- Escape characters
- The first string methods
- Why strings cannot be changed
On this page
Writing strings
const a = "double quotes";
const b = 'single quotes';
const c = `backticks`;Double and single quotes work the same. Pick one and use it everywhere (tools like Prettier do this for you). Backticks are special: they make template literals (below).
Quotes inside a string:
const msg = "It's fine"; single quote inside double quotes
const html = '<a href="/">'; double quotes inside single quotesLength and positions
Each character in a string has a position number called an index. Counting starts at 0, not 1.
const word = "HELLO";| Character | H | E | L | L | O |
|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 |
word.length 5 (how many characters)
word[0] "H" (first character)
word[4] "O"
word[word.length - 1] "O" (last character)
word.at(-1) "O" (last character, newer way)
word[10] undefined (no character there)The last index is always length - 1. Forgetting this causes "off-by-one" bugs, which are very common in interviews.
Joining strings
With +:
const first = "Sam";
const last = "Khan";
const full = first + " " + last; "Sam Khan"The + trap: if either side is a string, + joins instead of adding.
"5" + 2 "52"
5 + 2 7
"5" - 2 3 (minus always does maths, so "5" becomes 5)
"5" * 2 10This is the cause of many bugs with form input.
Template literals
Backtick strings let you put values straight into the text with ${ }.
const name = "Sam";
const items = 3;
const message = `Hi ${name}, you have ${items} items in your basket.`;Result: Hi Sam, you have 3 items in your basket.
Anything inside ${ } is worked out first:
const price = 4;
`Total: £${price * items}` "Total: £12"They can also go over several lines:
const html = `
<div class="card">
<h2>${name}</h2>
</div>
`;Use template literals whenever you mix text and values. They are easier to read than many + signs.
Escape characters
A backslash \ gives the next character a special meaning.
| Code | Meaning |
|---|---|
\n | New line |
\t | Tab |
\" | A double quote inside double quotes |
\' | A single quote inside single quotes |
\\ | A real backslash |
console.log("Line one\nLine two");Shows two lines.
Strings cannot be changed
Strings are immutable. Methods do not change the original string; they return a new one.
const word = "hello";
word.toUpperCase(); returns "HELLO"
console.log(word); still "hello"
const loud = word.toUpperCase(); save the new string
console.log(loud); "HELLO"Also, word[0] = "J" does nothing. To "change" a string, build a new one.
First string methods
A method is a function that belongs to a value. You call it with a dot: text.method().
| Method | Example | Result |
|---|---|---|
toUpperCase() | "hi".toUpperCase() | "HI" |
toLowerCase() | "HI".toLowerCase() | "hi" |
trim() | " hi ".trim() | "hi" (removes spaces at both ends) |
includes(x) | "hello".includes("ell") | true |
startsWith(x) | "hello".startsWith("he") | true |
endsWith(x) | "file.pdf".endsWith(".pdf") | true |
indexOf(x) | "hello".indexOf("l") | 2 (first position), or -1 if not found |
slice(start, end) | "hello".slice(1, 3) | "el" (end is not included) |
replace(a, b) | "a-b-c".replace("-", "+") | "a+b-c" (first only) |
replaceAll(a, b) | "a-b-c".replaceAll("-", "+") | "a+b+c" |
split(x) | "a,b,c".split(",") | ["a", "b", "c"] (an array) |
repeat(n) | "ab".repeat(3) | "ababab" |
padStart(n, x) | "7".padStart(2, "0") | "07" |
Part 5 covers more methods and regular expressions.
Comparing text without worrying about capitals
const input = " YES ";
input.trim().toLowerCase() === "yes" trueThis is a common pattern for checking user input.
Turning other values into strings
String(42) "42"
(42).toString() "42"
`${42}` "42"Common mistakes
- Forgetting that indexes start at 0.
- Using
word[word.length]for the last character (it isundefined). - Expecting
toUpperCase()to change the original variable. - Writing
${name}inside normal quotes. It only works with backticks. - Adding numbers that are really strings:
"5" + "5"is"55".
How to say it in an interview
"Strings are immutable sequences of characters indexed from zero, so methods like toUpperCase or replace return a new string. I use template literals with backticks for interpolation and multi-line strings. A key trap is that plus concatenates if either operand is a string, while minus and times convert to numbers."
Key words
| Word | Meaning |
|---|---|
| String | A piece of text |
| Index | The position of a character, starting at 0 |
| Concatenation | Joining strings together |
| Template literal | A backtick string that can include ${values} |
| Escape character | A backslash code such as \n |
| Method | A function that belongs to a value, called with a dot |
| Immutable | Cannot be changed after it is created |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.