JS Fundamentals
Template Literals & String Methods
Master JavaScript string manipulation. Explore ES6 template literals, expression interpolation, multi-line strings, and modern string search/mutation methods.
1. Introduction
Strings are sequences of characters used to represent text in an application. ES6 introduced Template Literals, which greatly simplified string interpolation and formatting compared to legacy concatenation.
2. Why It Matters
Proper string manipulation is essential for dynamic UI rendering, URL building, form input sanitization, and structured text parsing.
3. Real-World Analogy
Think of Writing a Form Letter:
- Traditional Concatenation: Printing out segments of a sentence on separate labels, and manually taping customer name labels in between. It is easy to make spacing mistakes.
- Template Literals: A pre-printed document with placeholders (like
Dear ${name}). The printer automatically fills in the placeholders, ensuring the layout remains consistent.
4. How It Works
Template literals are wrapped in backticks (`) instead of single or double quotes. They support:
• Multi-line Strings: Newlines inside backticks are preserved directly.
• String Interpolation: Inserting expressions inside \${expression} placeholders.
5. Core String Methods
| Method | Purpose | Example Output |
|---|---|---|
includes(substring) |
Checks if substring exists | "hello".includes("ll") // true |
startsWith(str) |
Checks prefix matching | "hello".startsWith("he") // true |
split(separator) |
Splits string into array | "a,b".split(",") // ["a", "b"] |
trim() |
Removes leading & trailing whitespace | " hi ".trim() // "hi" |
replace(target, replacement) |
Replaces first instance | "ab".replace("a", "x") // "xb" |
6. Practical Example
This script demonstrates template literals and basic string methods:
7. Common Mistakes
- Unescaped backticks: Forgetting to escape backticks (
\`) inside template literals crashes execution. - Assuming strings are mutable: JavaScript strings are completely immutable. Methods like
replaceortoUpperCasereturn a new string; they do not alter the original string variable.
8. Quick Quiz
Q1: Which method returns a new string containing characters extracted from a specific range of indices?
A) slice()
B) split()
Answer: A — slice(start, end) returns a portion of the string without modifying the original.
9. Scenario-Based Challenge
The URL Path Builder:
You need to build a dynamic URL path for an API request: /api/users/{userId}/posts?category={category}. If userId contains whitespace or special characters, explain how to clean the string before interpolating it.
10. Debugging Exercise
Identify why the validation fails to detect matching email domains:
const userEmail = ' User@domain.com ';
if (userEmail.endsWith('domain.com')) {
console.log('Domain matches');
} else {
console.log('Invalid Domain'); // prints this!
}
View Solution
Diagnosis: The string has leading/trailing spaces and uppercase characters, preventing it from matching the lowercase domain suffix.
Fix: Chain trim() and toLowerCase() before checking the suffix:
const cleanEmail = userEmail.trim().toLowerCase();
if (cleanEmail.endsWith('domain.com')) {
console.log('Domain matches');
}
11. Interview Questions
🟢 Q1: What are Tagged Template Literals?
Answer: Tagged Template Literals allow you to parse template literals using a function. The first argument of the tag function is an array of string literals, and the remaining arguments correspond to the evaluated expressions. This pattern is commonly used in CSS-in-JS libraries (like styled-components) and HTML sanitization libraries.
12. Production Considerations
- • XSS Prevention: Never interpolate unsanitized user inputs directly into HTML templates. Use specialized library encoders or DOM elements'
textContentproperty to prevent Cross-Site Scripting (XSS).