Skip to main content
Albero Academy

Strings & Regular Expressions

Work with text properly — the essential string methods, template literals, and a practical introduction to regular expressions.

Chapter 6JavaScript15 min readBeginner friendly
  • #JavaScript
  • #Strings
  • #Regex

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

everyday methods
const s = " Albero Academy ";
s.length // 17
s.trim() // "Albero Academy" (drop surrounding space)
s.toUpperCase() // " ALBERO ACADEMY "
s.toLowerCase()
s.replace("Academy", "Learn") // replace first match
s.replaceAll(" ", "-")
s.split(" ") // ["", "", "Albero", "Academy", "", ""]
find & extract
const email = "aanya@example.com";
email.includes("@") // true
email.startsWith("aanya") // true
email.endsWith(".com") // true
email.indexOf("@") // 5
email.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:

template literals
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:

regex basics
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"]
PatternMatches
\d \w \sdigit / word char / whitespace
+ * ?one-or-more / zero-or-more / optional
^ $start / end of string
[abc]any one of a, b, c
g iflags: 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

  1. 01Strings are immutable — methods return new strings; assign the result to keep it.
  2. 02Know trim, toUpperCase/Lowercase, replace/replaceAll, split, slice, includes, indexOf.
  3. 03Template literals interpolate ${…} and span multiple lines — prefer them to concatenation.
  4. 04A regex /pattern/ matches text; \d \w \s + * ? ^ $ [abc] and g/i flags cover most needs.
  5. 05Keep regex simple; validate complex formats on the server, not with a monster pattern.