Strings & Template Literals

🟨 JavaScript Lesson 4 Beginner

Strings store text sequences. JavaScript provides single quotes, double quotes, and backtick string representations for formatting interpolation.

1 String Pool & Template Strings

Template string literals use **backticks (``)** instead of standard quotes. They offer two major advantages:

  • Multi-line Support: You can write strings spanning multiple lines directly without using escape sequences like `\n`.
  • String Interpolation (`${expression}`): You can embed variables and mathematical calculations directly inside the string without clumsy concatenation using `+` signs.
2 Core String Methods

Let's run a program demonstrating slice, index searching, case transformations, and template literal substitution formatting:

JavaScript — String Manipulation ▶ Run Code
let text = "JavaScript Programming";

// Length and slices
console.log("Length: " + text.length);
console.log("Slice (0, 10): " + text.slice(0, 10));

// Replacements & case shifts
console.log("Upper Case: " + text.toUpperCase());
console.log("Replace Java: " + text.replace("Java", "Type"));

// Template Literal formatting
let course = "JavaScript";
let rating = 5;
let summary = `The ${course} course has a rating of ${rating}/5 stars.`;
console.log("Summary: " + summary);
3 Code Challenge
Challenge: Create variables storing a product name, price, and purchase quantity. Use template literals to compute the total cost and output a dynamic statement (e.g. `Purchased 3 Shirts for a total of $75`).