Why This Matters
Text is everywhere in programming — user names, messages, URLs, file paths, HTML, JSON, log output. A string is how programs represent text, and string manipulation is one of the most common operations you will perform.
Knowing how to search, slice, replace, and format strings fluently makes you dramatically faster at solving real problems. Every form validation, every URL parser, every template engine is built on string operations.
Define Terms
Visual Model
The full process at a glance. Click Start tour to walk through each step.
Strings are sequences of characters accessed by index, just like arrays — but immutable.
Code Example
// String basics
const greeting = "Hello, World!";
console.log(greeting.length); // 13
console.log(greeting[0]); // "H"
console.log(greeting.at(-1)); // "!"
// Template literals
const name = "Alice";
const age = 28;
console.log(`${name} is ${age} years old`); // Alice is 28 years old
// Searching
console.log(greeting.includes("World")); // true
console.log(greeting.indexOf("World")); // 7
console.log(greeting.startsWith("Hello")); // true
// Transforming (returns NEW string)
console.log(greeting.toUpperCase()); // HELLO, WORLD!
console.log(greeting.toLowerCase()); // hello, world!
console.log(greeting.replace("World", "JS")); // Hello, JS!
console.log(" spaces ".trim()); // "spaces"
// Slicing
console.log(greeting.slice(0, 5)); // "Hello"
console.log(greeting.slice(7)); // "World!"
// Split and join
const words = greeting.split(", ");
console.log(words); // ["Hello", "World!"]
console.log(words.join(" + ")); // "Hello + World!"Interactive Experiment
Try these exercises:
- Use template literals to build a sentence from three variables:
name,city,hobby. - Write a function that counts how many times a character appears in a string.
- Use
.split()to break a CSV line into an array, then.join()to rebuild it with a different delimiter. - What does
"abc".repeat(3)return? What about"hello"[100]? - Chain
.trim().toLowerCase().replace()to clean up messy user input.
Quick Quiz
Coding Challenge
Write a function called `toTitleCase` that takes a string and returns it in title case: the first letter of each word is capitalized, the rest are lowercase. Words are separated by spaces.
Real-World Usage
String manipulation powers nearly every application:
- Form validation: Checking email formats, trimming whitespace, enforcing password rules.
- URL routing: Parsing paths like
/users/123/profileinto segments with split. - Search: Case-insensitive matching with
.toLowerCase()and.includes(). - Templating: Building HTML, emails, and messages with template literals.
- Data parsing: CSV processing, log file analysis, JSON string handling.