Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Regular expressions (regex) are patterns used to find and match text. Think of them as super-powered search with special codes to find emails, phone numbers, or any text pattern!
Pattern between forward slashes
const regex = /hello/; const regex2 = /hello/gi; // with flags
Use when pattern comes from variable
const regex = new RegExp('hello');
const regex2 = new RegExp('hello', 'gi'); // with flagsBoth ways to create patterns
Check if pattern exists in string
const regex = /hello/;
console.log(regex.test('hello world')); // true
console.log(regex.test('goodbye')); // falseFind and extract matches
const text = 'cat bat rat'; const matches = text.match(/at/g); console.log(matches); // ['at', 'at', 'at']
Replace pattern with new text
const text = 'I love cats'; const newText = text.replace(/cats/, 'dogs'); console.log(newText); // 'I love dogs'
Using test(), match(), and replace()
Using special characters
Specifying repetition
Find all matches, not just first
Case-insensitive matching
^ and $ match start/end of each line
Using g, i, and m flags
/^[\w.-]+@[\w.-]+\.\w+$/
/^\d{3}-\d{3}-\d{4}$//^https?:\/\/[\w.-]+\.\w+/
/^(?=.*[a-z])(?=.*\d).{8,}$/Real-world form validation