Skip to content

Lesson 4 of 50JavaScript basics

Strings and Template Literals

Build, slice, search and clean up text with template literals and the string methods you will use every day, and put text on a page safely.

15 min read0/4 questions

Most of what a web app shows is text: names, prices, error messages, search results, the title of every page. Most of what it receives is text too, because whatever a person types into a form arrives as a string, even if it looks like a number. So a big share of everyday JavaScript is string work: cleaning up input, building messages, checking what something starts with, splitting a line into pieces. This lesson covers the methods you will reach for again and again, plus two traps: strange characters that are "longer" than they look, and putting user text into a page in a way that lets an attacker run code.

Writing strings

A string is a piece of text. You can write one with single quotes, double quotes or backticks:

const a = 'single quotes';
const b = "double quotes";
const c = `backticks`;

Single and double quotes behave exactly the same. Pick one and let your formatter (Prettier, for example) enforce it. Backticks create a template literal, which has extra powers you will see in a moment.

Escaping

What if the text contains the same quote you used to open it? You escape it with a backslash, which tells JavaScript "the next character is part of the text, not the end of the string". A backslash also starts a few special characters:

EscapeMeans
\" and \'A literal quote
\\A literal backslash
\nA new line
\tA tab
\u00e9A character by its Unicode code (here é)

Often you can avoid escaping by choosing the other quote: "It's fine" needs no backslash. Windows file paths are a classic place to forget: "C:\new" contains a new line, not the letters n, e, w. Write "C:\\new".

Template literals

You met template literals in the values and variables lesson: backtick strings that embed any expression with ${...}. Two more features make them the default choice for building text:

  • They can span several lines. The line breaks are kept exactly as you typed them.
  • The ${} can hold any expression: a calculation, a function call, a ternary, even another template literal.
JavaScript
const order = { id: 1042, items: 3, total: 27.5, express: true }; const receipt = `Order #${order.id}Items: ${order.items}Total: $${order.total.toFixed(2)}Delivery: ${order.express ? "Express" : "Standard"}`; console.log(receipt);console.log(`You have ${order.items} item${order.items === 1 ? "" : "s"} in your cart.`);
Output
Press Run (⌘ Enter) to see what happens.

The $$ in the total line is not special: the first $ is a normal dollar sign and the second starts the ${}. Change items to 1 and run it again to see the plural switch to singular.

One thing a template literal does not do is make text safe for HTML. It pastes whatever the value is straight in. That matters at the end of this lesson.

Length and indexing

Every string has a length, the number of characters it holds. Each character sits at an index, starting at 0, exactly like an array. You read one character with square brackets, or with at(), which also accepts negative numbers to count from the end.

"JavaScript" by index, and slice(0, 4)
J
0
a
1
v
2
a
3
S
4
c
5
r
6
i
7
p
8
t
9
length = 10

Ten characters, indexes 0 to 9. The last index is always length - 1.

1/4

Strings are immutable: no method changes the original. name.toUpperCase() returns a new string and leaves name alone. If you want to keep the result, assign it: name = name.trim(). Forgetting this is one of the most common beginner bugs, because the code runs without an error and simply does nothing visible.

The everyday methods

You do not need to memorise every string method. These cover most real work:

MethodReturnsExample
slice(start, end)Part of the string"hello".slice(1, 3) gives "el"
includes(text)true or false"hello".includes("ell")
startsWith(text) / endsWith(text)true or falseurl.startsWith("https://")
indexOf(text)First position, or -1"a-b-c".indexOf("-") gives 1
split(sep)An array of pieces"a,b,c".split(",")
trim()Without spaces at both ends" hi ".trim()
toUpperCase() / toLowerCase()Changed case"Ada".toLowerCase()
padStart(len, fill)Padded at the front"7".padStart(2, "0") gives "07"
replace(a, b) / replaceAll(a, b)Text swapped"a-b-c".replaceAll("-", " ")
repeat(n)Repeated text"ab".repeat(3)

join is the opposite of split, but it lives on arrays: ["a", "b"].join(", ") gives "a, b". Splitting, working on the array, then joining back is a pattern you will use constantly.

Here are the methods working together on realistic messy input:

JavaScript
const raw = " Ada LOVELACE , ada@Example.COM "; const [namePart, emailPart] = raw.split(",");const name = namePart.trim();const email = emailPart.trim().toLowerCase(); console.log(name);console.log(email, email.includes("@"), email.endsWith(".com")); // "Ada LOVELACE" -> "ada-lovelace", handy for URLsconst slug = name.toLowerCase().split(" ").join("-");console.log(slug); // Initials: map turns each word into its first letter (arrays lessons cover map)const initials = name.split(" ").map((word) => word[0]).join("");console.log(initials); // Zero-padded order numbers and timesconsole.log(String(42).padStart(6, "0"));console.log(`${String(9).padStart(2, "0")}:${String(5).padStart(2, "0")}`);
Output
Press Run (⌘ Enter) to see what happens.

The line const [namePart, emailPart] = raw.split(",") is destructuring: it takes the first two items of the array and gives them names. The destructuring lesson covers it fully.

Predict the outputJavaScript

What does this print?

const file = "holiday-photo.final.jpg";
const parts = file.split(".");
console.log(parts.length, parts.at(-1));
Need a nudge? Hints walk you through it.

replace vs replaceAll

replace with a plain string only changes the first match. This surprises almost everyone the first time.

"1-800-555".replace("-", "");    // "1800-555": only the first dash
"1-800-555".replaceAll("-", ""); // "1800555"

Before replaceAll arrived in 2021, people wrote replace(/-/g, ""), a regular expression (a pattern language for matching text) with the g ("global") flag. You will still see that form in older code. Both give the same result. Every modern browser and Node.js supports replaceAll.

Quick check
What does this return?
"red, green, blue".replace(", ", " / ")
Need a nudge? A hint rules out a wrong answer.
Match the pairs0/5 matched

Pick the method for each job.

Choose an item, then its match on the other side.

Comparing and searching

String comparison with === is exact and case sensitive: "Ada" === "ada" is false. To compare the way people expect, normalise both sides first, usually with trim().toLowerCase(). A search box that ignores case looks like this:

const matches = products.filter((p) =>
  p.name.toLowerCase().includes(query.trim().toLowerCase())
);

For sorting words alphabetically, use a.localeCompare(b), which knows about accents and different languages. The array methods lesson shows it in action.

Unicode gotchas

JavaScript stores strings as UTF-16, a way of encoding text in 16-bit chunks called code units. Common characters take one chunk, but many symbols, rarer scripts and most emoji take two. length counts chunks, not the characters a person sees, so some one-character strings have a length of 2, and slice can cut a character in half. Accented letters can also be written two ways: é as one character, or e followed by a separate accent mark, which look identical but are not ===. str.normalize() makes them match, and [...str].length counts real characters (code points) instead of chunks. For truly user-perceived characters (like a flag made of several code points), modern browsers have Intl.Segmenter.

JavaScript
const clef = "\u{1D11E}"; // a musical symbol outside the basic rangeconsole.log(clef.length, [...clef].length); const cafe1 = "caf\u00e9"; // é as one characterconst cafe2 = "cafe\u0301"; // e + a combining accentconsole.log(cafe1 === cafe2, cafe1.length, cafe2.length);console.log(cafe1.normalize() === cafe2.normalize());
Output
Press Run (⌘ Enter) to see what happens.

Putting text on a page safely

In the browser, you will often build text and put it into the page. There are two common properties for that, and the difference is a security issue, not a style choice.

const comment = '<img src=x onerror="alert(document.cookie)">';
 
// Dangerous: the string is parsed as HTML, so the onerror code runs
commentBox.innerHTML = `<p>${comment}</p>`;
 
// Safe: the string is shown as plain text, tags and all
commentBox.textContent = comment;

innerHTML treats the string as HTML and builds real elements from it. If any part of that string came from a user (a comment, a name, a search query in the URL), an attacker can inject an element that runs their JavaScript in your visitors' browsers. This is cross-site scripting (XSS), one of the most common web vulnerabilities. A template literal does not protect you: it only joins strings.

textContent treats the string as text. The browser shows <img ...> as visible characters and never runs it. Use textContent for anything that is just text, which is almost always. When you do need markup around user data, create the elements with document.createElement and set their textContent, as the DOM lesson shows. Frameworks like React escape text for you by default, which is one of the reasons they are popular.

Quick check
A profile page shows Hello, <name> where the name comes from the database. Which line is safe?
Need a nudge? A hint rules out a wrong answer.
Key terms
string
A piece of text. Immutable: methods return new strings instead of changing the original.
template literal
A backtick string that can embed ${expression} and span several lines.
escape
A backslash that makes the next character literal, or starts a special one like \n.
index
A character's position in a string, starting at 0. The last is length - 1.
UTF-16
How JavaScript stores text. Some characters take two code units, so length can overcount.
XSS
Cross-site scripting: an attacker's code runs in your page because user text was inserted as HTML.