Strings & template literals
Quotes, escapes, template literals and the string methods you will use every day.
Text is everywhere: names, messages, URLs, HTML, CSV files. In JavaScript, text is the string type. This lesson covers how to write strings, build them with template literals, and use the built-in methods you'll reach for every day.
Three ways to write a string#
Single and double quotes are identical — pick one and let a formatter enforce it. Backticks create template literals, which have superpowers.
Escape sequences
Use a backslash to include special characters:
Or avoid escaping by choosing the other quote: "It's here".
Template literals#
Backtick strings can interpolate any expression with ${...} and can span lines:
Compare the old way: name + " has finished " + done + " of " + total + " lessons." — template literals are far easier to read.
Security tip: building HTML with template literals and inserting it with
innerHTMLis dangerous if any value comes from a user. You'll learn the safe approach in the DOM lesson.
Length, indexes and characters#
Strings are immutable. Methods never change the original; they return a new string:
Everyday string methods#
Changing case and trimming
Trim and normalise user input before comparing or saving it.
Searching
Searches are case-sensitive. For case-insensitive checks, lower-case both sides first.
Extracting parts
Prefer slice — it's consistent with arrays and supports negative indexes.
Splitting and joining
Replacing
Padding and repeating
padStart is perfect for times ("05") and invoice numbers.
Comparing strings#
Converting to and from strings#
Unicode and emoji#
JavaScript strings are UTF-16. Most characters take one "code unit", but emoji and some symbols take two:
When counting user-visible characters (e.g. a tweet-length limit), use [...str].length. For full accuracy with combined emoji like 👨👩👧, use Intl.Segmenter.
A worked example: making a URL slug#
Chaining methods like this works because each one returns a new string. In the Regular expressions lesson you'll write a more robust version.
Common mistakes#
- Expecting
replaceto replace everything — usereplaceAll. - Forgetting strings are immutable:
name.toUpperCase();on its own line does nothing useful; assign the result. - Using
+with numbers from inputs:"2" + "2"is"22". - Using
substr— it's deprecated. Useslice.
What's next#
Now that you can build and inspect text, it's time to make decisions with conditionals.
Check your understanding
Quick quiz
1.What does
"Elephantoo".slice(-3)return?2.Given
const s = "hello"; s[0] = "J";, what issafterwards?3.Which method replaces **every** occurrence of
"-"in a string?
Finished reading?
Mark this lesson complete to track your progress.