Regular Expressions in JavaScript: The Basics

JavaScript’s regex support is built directly into the language via the RegExp object and string methods — no separate library needed for most pattern matching needs.

const emailPattern = /^[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}$/;
emailPattern.test('user@example.com'); // true

const text = "Contact: alice@example.com or bob@test.org";
text.match(/[\w.+-]+@[\w-]+\.\w+/g); // ['alice@example.com', 'bob@test.org']

// Named capture groups
const dateMatch = "2025-09-08".match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
console.log(dateMatch.groups.year); // '2025'

// Replace with a function
"hello world".replace(/\w+/g, word => word[0].toUpperCase() + word.slice(1));
// 'Hello World'

The g flag matters a lot: without it, .match() returns only the first match (plus capture group details); with it, you get all matches but lose the capture group breakdown — a common source of confusion when switching between the two.