beginner
Step 4 of 20
Strings and Template Literals
JavaScript Programming
Strings and Template Literals
Strings are sequences of characters used to represent text in JavaScript. Modern JavaScript (ES6+) introduced template literals — a powerful new way to work with strings using backtick syntax that supports multi-line strings, embedded expressions, and tagged templates. JavaScript strings are immutable (like Python) and come with a rich set of built-in methods for searching, extracting, and transforming text. Whether you are building user interfaces, processing data, or generating HTML, strings are one of the most frequently used data types.
Creating Strings
// Three ways to create strings
const single = 'Hello, World!';
const double = "Hello, World!";
const template = `Hello, World!`;
// Template literals — embedded expressions
const name = "Alice";
const age = 30;
const greeting = `Hello, ${name}! You are ${age} years old.`;
console.log(greeting); // "Hello, Alice! You are 30 years old."
// Expressions inside template literals
console.log(`2 + 3 = ${2 + 3}`);
console.log(`Uppercase: ${name.toUpperCase()}`);
console.log(`Status: ${age >= 18 ? "adult" : "minor"}`);
// Multi-line strings
const poem = `Roses are red,
Violets are blue,
JavaScript is fun,
And so are you.`;
// Without template literals, you'd need:
const old = "Line 1
" +
"Line 2
" +
"Line 3";
Essential String Methods
const text = " Hello, JavaScript World! ";
// Length
console.log(text.length); // 30
// Case conversion
console.log(text.toUpperCase()); // " HELLO, JAVASCRIPT WORLD! "
console.log(text.toLowerCase()); // " hello, javascript world! "
// Trimming whitespace
console.log(text.trim()); // "Hello, JavaScript World!"
console.log(text.trimStart()); // "Hello, JavaScript World! "
console.log(text.trimEnd()); // " Hello, JavaScript World!"
// Searching
console.log(text.includes("JavaScript")); // true
console.log(text.startsWith(" Hello")); // true
console.log(text.endsWith("! ")); // true
console.log(text.indexOf("JavaScript")); // 9
console.log(text.lastIndexOf("o")); // 24
// Extracting substrings
console.log(text.slice(8, 18)); // "JavaScript"
console.log(text.slice(-8)); // "World! "
console.log(text.substring(8, 18)); // "JavaScript"
// Replacing
console.log(text.replace("World", "Earth"));
console.log(text.replaceAll(" ", "-")); // Replace all spaces
// Splitting
const csv = "apple,banana,cherry,date";
const fruits = csv.split(",");
console.log(fruits); // ["apple", "banana", "cherry", "date"]
const words = "Hello World".split("");
console.log(words); // ["H", "e", "l", "l", "o", " ", "W", ...]
// Joining (array method, not string)
console.log(fruits.join(" | ")); // "apple | banana | cherry | date"
// Padding
console.log("5".padStart(3, "0")); // "005"
console.log("Hi".padEnd(10, ".")); // "Hi........"
// Repeating
console.log("ha".repeat(3)); // "hahaha"
console.log("-".repeat(40)); // "----------------------------------------"
// Character access
console.log("Hello"[0]); // "H"
console.log("Hello".charAt(4)); // "o"
console.log("Hello".at(-1)); // "o" (ES2022)
Regular Expressions with Strings
// Test if a string matches a pattern
const email = "alice@example.com";
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailRegex.test(email)); // true
// Match — find pattern occurrences
const text2 = "Call 555-1234 or 555-5678";
const phoneRegex = /\d{3}-\d{4}/g;
const matches = text2.match(phoneRegex);
console.log(matches); // ["555-1234", "555-5678"]
// Replace with regex
const cleaned = "Hello World JS".replace(/\s+/g, " ");
console.log(cleaned); // "Hello World JS"
// Named capture groups
const dateStr = "2024-03-15";
const dateRegex = /(?\d{4})-(?\d{2})-(?\d{2})/;
const { groups } = dateStr.match(dateRegex);
console.log(groups.year, groups.month, groups.day); // "2024" "03" "15"
Building HTML with Template Literals
// Generating HTML (common in web apps)
const users = [
{ name: "Alice", role: "Admin" },
{ name: "Bob", role: "User" },
{ name: "Charlie", role: "User" }
];
const html = `
<ul class="user-list">
${users.map(user => `
<li class="user-item ${user.role.toLowerCase()}">
<strong>${user.name}</strong>
<span>${user.role}</span>
</li>
`).join("")}
</ul>
`;
console.log(html);
Pro tip: Template literals are the modern way to build strings in JavaScript. They eliminate the need for string concatenation with+, support multi-line strings naturally, and allow any JavaScript expression inside${}. Use them whenever you need to embed variables or expressions in strings.
Key Takeaways
- Template literals (backticks) support embedded expressions (
${expr}), multi-line strings, and are the preferred way to build strings. - Essential methods:
includes(),startsWith(),slice(),split(),replace(),trim(),padStart(). - Strings are immutable — methods return new strings without modifying the original.
- Regular expressions provide powerful pattern matching with
test(),match(), andreplace(). - Use template literals for generating HTML templates by combining
map()andjoin()with embedded expressions.