⚡ Lesson 24 of 30
Regular Expressions
Search, test, match, and replace text using JavaScript's regular expression engine.
Creating RegExp
Use a regex literal /.../ or the RegExp constructor:
const re1 = /hello/i; // literal (case-insensitive)
const re2 = new RegExp("hello", "i"); // constructor
console.log(re1.test("Hello World")); // true
console.log(re2.test("Hello World")); // true
Flags
const text = "Cat cat CAT";
console.log(text.match(/cat/g)); // ["cat"]
console.log(text.match(/cat/gi)); // ["Cat","cat","CAT"]
console.log(text.match(/cat/m)); // ["Cat"] (multiline)
console.log(/cat/s.test("ca\nt")); // true (dotAll)
Character Classes & Quantifiers
// \d digit, \w word char, \s whitespace, . any char
const dateRe = /\d{4}-\d{2}-\d{2}/;
console.log(dateRe.test("2026-01-15")); // true
const emailRe = /^[\w.+%-]+@[\w-]+\.[a-z]{2,}$/i;
console.log(emailRe.test("[email protected]")); // true
Capture Groups
const iso = "2026-07-04";
const match = iso.match(/(\d{4})-(\d{2})-(\d{2})/);
if (match) {
const [, year, month, day] = match;
console.log(year, month, day); // 2026 07 04
}
// Named groups (cleaner)
const { groups } = iso.match(/(?\d{4})-(?\d{2})-(?\d{2})/);
console.log(groups.y, groups.m, groups.d); // 2026 07 04
replace & replaceAll
const text = "Hello World! Hello JS!";
// Replace first match
console.log(text.replace(/Hello/, "Hi"));
// "Hi World! Hello JS!"
// Replace all with callback
console.log(text.replace(/Hello/g, m => m.toUpperCase()));
// "HELLO World! HELLO JS!"