Text is everywhere — names, emails, URLs, user input. JavaScript strings are immutable (every "change" returns a new string), and come with a rich set of methods. This chapter covers the ones you'll actually use, plus a practical first look at regular expressions for matching and validating patterns.
String methods
const s = " Albero Academy ";s.length // 17s.trim() // "Albero Academy" (drop surrounding space)s.toUpperCase() // " ALBERO ACADEMY "s.toLowerCase()s.replace("Academy", "Learn") // replace first matchs.replaceAll(" ", "-")s.split(" ") // ["", "", "Albero", "Academy", "", ""]
Searching & slicing
const email = "aanya@example.com";email.includes("@") // trueemail.startsWith("aanya") // trueemail.endsWith(".com") // trueemail.indexOf("@") // 5email.slice(0, 5) // "aanya" (start, end)email.slice(6) // "example.com"email.at(-1) // "m" (last char)
Template literals
Backtick strings interpolate expressions with ${…} and span multiple lines — far cleaner than concatenation:
const name = "Rohan", pkg = 8;const msg = `${name} was placed at ₹${pkg} LPA`;const html = `<div class="card"><h3>${name}</h3></div>`;
Regular expressions
A regex is a pattern for matching text. It looks cryptic but a little goes a long way — validating emails, extracting numbers, cleaning input. Write one between slashes:
const re = /\d+/; // one or more digits"Batch 2026".match(/\d+/) // ["2026"]/^\S+@\S+\.\S+$/.test("a@b.com") // true — rough email check"a1b2c3".replace(/\d/g, "") // "abc" (g = all matches)"one,two;three".split(/[,;]/) // ["one","two","three"]
| Pattern | Matches |
|---|---|
\d \w \s | digit / word char / whitespace |
+ * ? | one-or-more / zero-or-more / optional |
^ $ | start / end of string |
[abc] | any one of a, b, c |
g i | flags: global / case-insensitive |
Practice
Write a function that takes a messy full name (extra spaces, mixed case) and returns it trimmed and title-cased. Then write a regex that extracts all the numbers from a string like "3 batches, 42 seats".
Key takeaways
- 01Strings are immutable — methods return new strings; assign the result to keep it.
- 02Know trim, toUpperCase/Lowercase, replace/replaceAll, split, slice, includes, indexOf.
- 03Template literals interpolate ${…} and span multiple lines — prefer them to concatenation.
- 04A regex /pattern/ matches text; \d \w \s + * ? ^ $ [abc] and g/i flags cover most needs.
- 05Keep regex simple; validate complex formats on the server, not with a monster pattern.
