🌱 Phase 1 · Foundations 🟢 Beginner MODULE 03

Strings & Template Literals

⏱️ 40 min read
📖 Theory + Code
🧩 5 Quiz Questions
🏗️ 1 Challenge
Your progress in Phase 121%
🎯 What you'll learn: Creating strings with single, double, and backtick quotes, essential string methods like slice, includes, replace, split, powerful template literals with ${}, and the concept of string immutability.

Creating Strings

In JavaScript, you can create strings using three types of quotes. Each has its use case, but backtick strings (template literals) are the most powerful and flexible — use them by default in modern JS.

'Single quotes'
Classic way — simple strings with no special features
let name = 'Alice';
"Double quotes"
Functionally identical to single quotes in JS
let name = "Bob";
`Backticks`
Template literals — supports expressions, multi-line
let msg = `Hello, ${name}!`;
Escaping quotes
Use backslash to include the same quote type inside
let s = "She said \"hi\"";
creating-strings.js
JS
let name1 = 'Alice';        // single quotes
let name2 = "Bob";          // double quotes
let greeting = `Hello!`;   // backtick (template literal)

// Strings with special characters
let msg1 = "She said \"hello\"";  // escaped double quotes
let msg2 = 'It\'s great!';        // escaped single quote
let msg3 = `No escaping needed for "quotes" or 'apostrophes'`; // backtick wins!

console.log(msg1);  // She said "hello"
console.log(msg2);  // It's great!
console.log(msg3);  // No escaping needed for "quotes" or 'apostrophes'
Use backtick strings by default in modern JS
Template literals (backticks) are the most flexible string type — they support multi-line text, embedded expressions with ${}, and no need to escape common quotes. Make them your default choice in all modern JavaScript.

String Length

Every string has a .length property that tells you how many characters it contains — including spaces, punctuation, and symbols.

string-length.js
JS
let str = "Hello, World!";
console.log(str.length);   // 13

console.log("JavaScript".length);  // 10
console.log("".length);            // 0  — empty string
console.log("  ".length);           // 2  — spaces count!

// Real-world: validate minimum input length
let username = "js_dev";
if (username.length < 3) {
  console.log("Username too short!");
} else {
  console.log(`Username OK — ${username.length} characters`);
}
💡
.length is a property, not a method — no parentheses needed!
Write str.length, NOT str.length(). Adding parentheses will throw a TypeError because .length is a property (a value), not a callable function. This is a common beginner mistake.

Accessing Characters (Indexing)

Strings are zero-indexed — the first character is at position 0, not 1. You can access individual characters using bracket notation or string methods.

string-indexing.js
JS
let lang = "JavaScript";
//           J  a  v  a  S  c  r  i  p  t
//           0  1  2  3  4  5  6  7  8  9

// Bracket notation (most common)
console.log(lang[0]);   // "J"  — first character
console.log(lang[4]);   // "S"
console.log(lang[9]);   // "t"  — last character

// Get the last character dynamically
console.log(lang[lang.length - 1]);  // "t"

// .charAt(index) — same as bracket notation
console.log(lang.charAt(0));    // "J"
console.log(lang.charAt(4));    // "S"

// .at(index) — ES2022: supports NEGATIVE indexes!
console.log(lang.at(-1));  // "t"  — last character
console.log(lang.at(-6));  // "S"  — 6th from end

// Out of bounds returns undefined (not an error)
console.log(lang[99]);  // undefined

Essential String Methods

JavaScript strings have 40+ built-in methods. Here are the ones you'll reach for every day. Call them with dot notation: string.method().

.toUpperCase() / .toLowerCase()

case-methods.js
JS
let city = "karachi";
console.log(city.toUpperCase());    // "KARACHI"
console.log("LONDON".toLowerCase()); // "london"

// Real-world: case-insensitive comparison
let input = "JavaScript";
console.log(input.toLowerCase() === "javascript"); // true

.trim() / .trimStart() / .trimEnd()

trim-methods.js
JS
let email = "  user@example.com  ";
console.log(email.trim());       // "user@example.com" — removes both ends
console.log(email.trimStart());  // "user@example.com  " — left only
console.log(email.trimEnd());    // "  user@example.com" — right only

.includes(searchStr)

includes-method.js
JS
let bio = "I love JavaScript";
console.log(bio.includes("JavaScript")); // true
console.log(bio.includes("Python"));     // false
console.log(bio.includes("javascript")); // false (case-sensitive!)

.indexOf(str) / .lastIndexOf(str)

indexof-methods.js
JS
let sentence = "The cat sat on the mat";
console.log(sentence.indexOf("at"));     // 5  — first occurrence
console.log(sentence.lastIndexOf("at")); // 20 — last occurrence
console.log(sentence.indexOf("dog"));    // -1 — not found

.startsWith() / .endsWith()

starts-ends.js
JS
let filename = "report.pdf";
console.log(filename.endsWith(".pdf"));   // true
console.log(filename.startsWith("rep"));  // true
console.log(filename.endsWith(".csv"));   // false

.slice(start, end)

slice-method.js
JS
let text = "JavaScript";
//           J  a  v  a  S  c  r  i  p  t
//           0  1  2  3  4  5  6  7  8  9

console.log(text.slice(0, 4));  // "Java"  — index 0,1,2,3 (4 excluded)
console.log(text.slice(4));     // "Script" — from index 4 to end
console.log(text.slice(-6));    // "Script" — negative = count from end
console.log(text.slice(0, -6)); // "Java"   — all except last 6

.replace(old, new) / .replaceAll(old, new)

replace-methods.js
JS
let msg = "I love cats. Cats are great!";
console.log(msg.replace("cats", "dogs"));    // "I love dogs. Cats are great!" — first only!
console.log(msg.replaceAll("ats", "ogs")); // "I love cogs. Cogs are great!" — all occurrences

.split(separator)

split-method.js
JS
let csv = "apple,banana,cherry";
let fruits = csv.split(",");
console.log(fruits); // ["apple", "banana", "cherry"]

// Split into individual characters
console.log("hello".split("")); // ["h","e","l","l","o"]

// Split by space
let words = "Hello World JS".split(" ");
console.log(words); // ["Hello", "World", "JS"]

.repeat(n) / .padStart() / .padEnd()

repeat-pad.js
JS
// .repeat(n) — repeat string n times
console.log("Ha".repeat(3));   // "HaHaHa"
console.log("=".repeat(20));  // "===================="

// .padStart(length, char) — pad from the left
console.log("5".padStart(3, "0")); // "005"  — great for IDs!
console.log("7".padStart(5, "0")); // "00007"

// .padEnd(length, char) — pad from the right
console.log("Hi".padEnd(10, "."));   // "Hi........"
console.log("Name".padEnd(10, " "));  // "Name      " (space padding)

Template Literals (Backticks)

Template literals are JavaScript's supercharged strings. They use backtick characters (`) and let you embed any expression directly inside using ${expression}. They also support multi-line strings natively — no more \n hacks.

template-literals.js
JS
const name = "Aisha";
const age = 22;
const city = "Karachi";

// Basic string interpolation — embed variables with ${}
console.log(`Hello, my name is ${name}!`);
console.log(`I am ${age} years old and live in ${city}.`);
console.log(`Next year I'll be ${age + 1}.`);  // expressions work too!

// Embed complex expressions
const price = 9.99;
const qty = 3;
console.log(`Total: $${(price * qty).toFixed(2)}`);  // Total: $29.97

// Multi-line string — no \n needed!
const poem = `Roses are red,
Violets are blue,
JavaScript is awesome,
And so are you!`;
console.log(poem);

// Call functions inside template literals
const upper = str => str.toUpperCase();
console.log(`Welcome, ${upper(name)}!`);  // "Welcome, AISHA!"
Template literals are a game-changer — learn them well
You'll use template literals constantly in real JS projects — for building HTML strings, API URLs, log messages, UI text, and more. Inside ${} you can put any valid JavaScript expression: variables, arithmetic, function calls, ternaries, and more.

String Immutability

JavaScript strings are immutable — once created, you cannot change individual characters. Trying to do so silently fails (no error, no change). Instead, you must always create a new string.

immutability.js
JS
let word = "hello";
word[0] = "H";          // silently fails — no error!
console.log(word);      // still "hello" — nothing changed

// Instead, create a new string:
word = "H" + word.slice(1);
console.log(word);      // "Hello" — new string created

// All methods return NEW strings — original is untouched
let original = "JavaScript";
let upper = original.toUpperCase();
console.log(original); // "JavaScript" — unchanged!
console.log(upper);    // "JAVASCRIPT" — new string
💡
String methods always return NEW strings — they never modify the original
This is why you must assign the result: str = str.toUpperCase(). If you just call str.toUpperCase() without assigning, the result is lost and str stays unchanged. This is a very common mistake!

Method Chaining

Because each string method returns a new string, you can chain multiple methods in a single expression. This is a powerful pattern for cleaning and transforming data.

method-chaining.js
JS
// Chain methods left to right — each operates on the result of the previous
const userInput = "  Hello, World!  ";
const cleaned = userInput.trim().toLowerCase().replace("hello", "hi");
console.log(cleaned);  // "hi, world!"

// Real-world: format a URL slug from a blog title
const title = "  My Awesome Blog Post!  ";
const slug = title
  .trim()                          // remove spaces: "My Awesome Blog Post!"
  .toLowerCase()                   // lowercase: "my awesome blog post!"
  .replace(/\s+/g, "-")          // spaces → dashes: "my-awesome-blog-post!"
  .replace(/[^a-z0-9-]/g, "");  // remove non-alphanumeric: "my-awesome-blog-post"
console.log(slug);  // "my-awesome-blog-post"

Regular Expressions — Quick Intro

String methods like .replace() and .test() can work with regular expressions (regex) — powerful pattern matchers that can search, validate, and transform text with incredible precision.

regex-intro.js
JS
// Basic regex syntax: /pattern/flags
const email = "user@example.com";
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailRegex.test(email));  // true — valid email format
console.log(emailRegex.test("not-valid")); // false

// replace with regex — the 'g' flag means replace ALL occurrences
const text = "foo bar baz bar foo";
console.log(text.replace(/bar/g, "---")); // "foo --- baz --- foo"

// Match digits
const phone = "Call 0300-1234567 now";
const digits = phone.match(/\d+/g);
console.log(digits);  // ["0300", "1234567"]
💡
Regular expressions are powerful pattern matchers
We're just scratching the surface here. Regex can match complex patterns — emails, phone numbers, URLs, dates, and more. We'll cover them in depth in the Advanced JS phase. For now, just know they exist and can be passed to .replace(), .match(), and .test().

Summary

1
Three ways to create strings
Single quotes, double quotes, and backticks (template literals). Use backticks by default in modern JS.
2
.length and indexing
Access characters with bracket notation (zero-indexed). Use .at(-1) for the last character with negative indexing.
3
Essential methods
.toUpperCase(), .trim(), .includes(), .slice(), .replace(), .split(), .padStart() — your daily toolkit.
4
Template literals
Embed any expression with ${}, write multi-line strings naturally. The modern, preferred way to build dynamic strings.
5
Strings are immutable
Methods return NEW strings — they never modify the original. Always assign the result back if you want to keep it.
🧩 Knowledge Check
5 questions — test your mastery of JavaScript Strings & Template Literals
1. What is the result of "Hello".length in JavaScript?
2. Which string method removes whitespace from both ends of a string?
3. What does the `Hello ${name}!` syntax in JavaScript use?
4. What is the result of "JavaScript".slice(4)?
5. Are JavaScript strings mutable (can you change individual characters)?
🏗️
Coding Challenge — Build a Name Formatter Function
Apply string methods, template literals, and chaining
Task: Create a function called formatName that:

1. Takes a raw input string like " john doe "
2. Trims whitespace
3. Splits into first and last name
4. Capitalizes the first letter of each
5. Returns a formatted string: "John Doe"

Also create a function called makeSlug(title) that converts "My Blog Post Title!" to "my-blog-post-title".

Test both functions with at least 3 different inputs.
💡 Show hints
  • Use .trim() then .split(" ") to get name parts
  • Filter out empty strings from split with .filter(Boolean)
  • Capitalize: word[0].toUpperCase() + word.slice(1)
  • Use .map() to capitalize each word, then .join(" ")
  • For slug: .toLowerCase().trim().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "")
name-formatter.js — Sample Solution
JS
// ── Name Formatter ───────────────────────────────
function formatName(rawInput) {
  return rawInput
    .trim()                          // remove leading/trailing spaces
    .split(/\s+/)                    // split on one or more spaces
    .filter(Boolean)                 // remove empty strings
    .map(word => word[0].toUpperCase() + word.slice(1).toLowerCase())
    .join(" ");                      // rejoin with single space
}

// ── URL Slug Generator ───────────────────────────
function makeSlug(title) {
  return title
    .trim()                          // remove edge spaces
    .toLowerCase()                   // all lowercase
    .replace(/\s+/g, "-")          // spaces → dashes
    .replace(/[^a-z0-9-]/g, "");  // remove special chars
}

// ── Test it out ──────────────────────────────────
console.log(formatName("  john   doe  "));     // "John Doe"
console.log(formatName("AISHA khan"));         // "Aisha Khan"
console.log(formatName("  ali   RAZA  "));      // "Ali Raza"

console.log(makeSlug("My Blog Post Title!"));  // "my-blog-post-title"
console.log(makeSlug("  10 Awesome JS Tips  ")); // "10-awesome-js-tips"
console.log(makeSlug("What's new in ES2024?")); // "whats-new-in-es2024"
Finished this lesson?
Mark it complete to track your progress.
🎉
Lesson 3 Complete!
You now master JavaScript strings — one of the most used data types in every real-world app.
← Course Home
Phase 1 · FoundationsLesson 3 of 7