By the end of this lesson, you will be able to clean, extract, transform, and split JavaScript strings using common methods such as trim, slice, replace, and split.
What it is
JavaScript strings are immutable sequences of characters. String methods return new strings instead of changing the original. Think of a string as a row of boxes with indexes starting at 0. Methods like slice copy a range, replace swaps text, split breaks a string into an array, and trim removes surrounding whitespace. Related terms include substring, indexOf, includes, toUpperCase, and regular expressions.
Why it matters
- Normalize user input before validation or storage.
- Extract parts of filenames, URLs, or CSV lines.
- Replace placeholders or sanitize simple text.
- Convert delimited strings into arrays for processing.
- Remove accidental spaces from form fields.
Syntax or steps
The smallest useful pattern is: start with a string, call a method, and store the returned value.
const raw = " hello world ";
const clean = raw.trim();
const first = clean.slice(0, 5);
const changed = clean.replace("world", "JavaScript");
const parts = clean.split(" ");
Because strings are immutable, raw.trim() does not change raw; it returns a new string.
Example
const input = " user@example.com ";
const email = input.trim();
const domain = email.slice(email.indexOf("@") + 1);
const masked = email.replace("user", "****");
const parts = email.split("@");
console.log(email); // "user@example.com"
console.log(domain); // "example.com"
console.log(masked); // "****@example.com"
console.log(parts); // ["user", "example.com"]
Part by part:
input.trim()removes spaces from both ends.email.indexOf("@")finds the position of@; adding1starts after it.email.slice(...)copies from that position to the end.email.replace("user", "****")replaces the first match only.email.split("@")creates an array of the text before and after@.
Common mistakes
- Expecting methods to mutate the original string. Fix: assign the result to a variable.
- Using
replace("a", "b")and thinking it replaces every match. Fix: usereplaceAll("a", "b")or a global regular expression. - Calling
slicewith wrong indexes. Fix: rememberslice(start, end)includesstartbut excludesend. - Splitting on a character that does not exist. Fix: check with
includesor handle the single-item array result.
When to use it
Use simple string methods for predictable text. Use regular expressions when the pattern is complex.
| Task | Use | Example |
|---|---|---|
| Remove spaces | trim |
" hi ".trim() |
| Get a known range | slice |
"abc".slice(0, 2) |
| Replace one fixed word | replace |
"a b".replace("b", "c") |
| Replace all fixed words | replaceAll |
"a a".replaceAll("a", "b") |
| Break into array | split |
"a,b".split(",") |
Practice
Guided exercise: clean a filename and extract its extension.
const file = " report.final.pdf ";
const name = file.trim();
const extension = name.slice(name.lastIndexOf(".") + 1);
console.log(extension); // "pdf"
Challenge: convert "apple,banana,cherry" into an array of capitalized words.
Solution hint: use split(","), then map each item to trim() and toUpperCase().
Quick check
Question: What does "hello".slice(1, 3) return?
Answer: "el", because index 1 is included and index 3 is excluded.
Summary
JavaScript string methods are tools for producing new strings or arrays from existing text. The key mental model is immutability: call the method, capture the result, and choose the simplest method that matches the task.