Code Example
// Create regex
const regex1 = /pattern/gi; // literal
const regex2 = new RegExp('pattern', 'gi'); // constructor
// Test if matches
const emailRegex = /^[\w.-]+@[\w.-]+\.[a-z]{2,}$/i;
emailRegex.test('user@example.com'); // true
// Find matches
const text = 'Contact us at info@example.com or support@test.com';
const emails = text.match(/[\w.-]+@[\w.-]+\.[a-z]{2,}/gi);
// ['info@example.com', 'support@test.com']
// Replace
const censored = 'My password is secret123'.replace(/secret\d+/, '***');
// 'My password is ***'
// Replace with function
const upper = 'hello world'.replace(/\b\w/g, c => c.toUpperCase());
// 'Hello World'
// Extract groups
const dateRegex = /(\d{4})-(\d{2})-(\d{2})/;
const match = '2025-01-27'.match(dateRegex);
// match[1] = '2025', match[2] = '01', match[3] = '27'
// Named groups (ES2018+)
const namedRegex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const { groups } = '2025-01-27'.match(namedRegex);
// groups.year = '2025'
Key Points: JavaScript regex supports literal /pattern/ or RegExp constructor. Use test() for boolean, match() for array, replace() for substitution.