Template Literals & String Methods
Template literals (backticks) are the modern way to work with strings — embedding variables, multi-line text, and expressions. String methods let you search, transform, and manipulate text, which is essential for handling user input, formatting, and data processing.
Template Literals & String Methods
- Template literals — Use backticks: `Hello, ${name}!`. Embed variables and expressions with ${}
- Multi-line strings — Template literals support line breaks without \n
- .length — Get string length: 'hello'.length = 5
- .toUpperCase() / .toLowerCase() — Transform case
- .trim() — Remove whitespace from both ends. Essential for form input cleaning
- .includes() / .startsWith() / .endsWith() — Search within strings
- .slice(start, end) — Extract part of string: 'Hello'.slice(0, 3) = 'Hel'
- .split() — Split string into array: 'a,b,c'.split(',') = ['a', 'b', 'c']
- .replace() / .replaceAll() — Replace text within strings
String Methods Code
// Template literals
const name = "Alice";
const age = 25;
console.log(`Hello, ${name}! You are ${age} years old.`);
console.log(`Next year you'll be ${age + 1}.`);
// Multi-line
const html = `
<div class="card">
<h2>${name}</h2>
<p>Age: ${age}</p>
</div>
`;
// String methods
const text = " Hello, World! ";
console.log(text.trim()); // "Hello, World!"
console.log(text.trim().length); // 13
console.log("hello".toUpperCase()); // "HELLO"
console.log("HELLO".toLowerCase()); // "hello"
console.log("JavaScript".includes("Script")); // true
console.log("JavaScript".startsWith("Java")); // true
console.log("file.pdf".endsWith(".pdf")); // true
console.log("Hello World".slice(0, 5)); // "Hello"
console.log("a,b,c,d".split(",")); // ["a","b","c","d"]
console.log("Hello World".replace("World", "JS")); // "Hello JS"Tip
Tip
Use template literals (backticks) for any string that includes variables or expressions. The ${} syntax is cleaner than concatenation and supports multi-line text naturally. It's the standard in modern frameworks like React.
Use backticks for strings with variables.
Common Mistake
Warning
Using regular quotes for strings with variables leads to clunky concatenation: 'Hello ' + name + ', age ' + age. Use backticks instead: `Hello ${name}, age ${age}`. Remember: backticks are a different key than single quotes (usually below Escape).
Practice Task
Note
Build a user greeting function: (1) Use template literals to create a multi-line HTML card with name, age, and email. (2) Use .trim() to clean whitespace from user input. (3) Chain .toLowerCase().includes() to search within a string.
Quick Quiz
Key Takeaways
- Template literals (backticks) are the modern way to work with strings — embedding variables, multi-line text, and expressions.
- Template literals — Use backticks: `Hello, ${name}!`. Embed variables and expressions with ${}
- Multi-line strings — Template literals support line breaks without \n
- .length — Get string length: 'hello'.length = 5