Regular expressions (RegExp) are patterns used to match character combinations in strings. In JavaScript, regular expressions are objects created via literal notation (/pattern/flags) or the RegExp constructor.
flowchart TD
RegExpSyntax["/pattern/flags"] --> Pattern["Pattern: ^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$"]
RegExpSyntax --> Flags["Flags: g (global), i (ignoreCase), m (multiline), u (unicode)"]
| Method | Source Object | Return Value | Primary Purpose |
|---|---|---|---|
regex.test(str) |
RegExp |
boolean |
Quick pattern validation check (e.g. Email / Password format). |
regex.exec(str) |
RegExp |
Array / null |
Detailed match result with capture groups. |
str.match(regex) |
String |
Array / null |
Extracting array of matching substrings. |
str.replace(rgx, sub) |
String |
New String | Replacing matched pattern with new string. |
// Demonstrating RegExp validation, extraction, and replacement
// 1. Email Validation with regex.test()
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const sampleEmail = "[email protected]";
console.log(`Is valid email? ${emailPattern.test(sampleEmail)}`); // true
// 2. Extracting Data using Capture Groups and exec()
const datePattern = /(\d{4})-(\d{2})-(\d{2})/; // YYYY-MM-DD
const textLog = "Created on 2026-08-13 in system log.";
const matchResult = datePattern.exec(textLog);
if (matchResult) {
console.log(`Full Match: ${matchResult[0]}`); // "2026-08-13"
console.log(`Year: ${matchResult[1]}, Month: ${matchResult[2]}, Day: ${matchResult[3]}`);
}
// 3. String Replacement with RegExp
const formattedPhone = "123-456-7890".replace(/-/g, ""); // Remove all hyphens
console.log(`Clean Phone Digits: ${formattedPhone}`); // "1234567890"
/pattern/g when the regular expression pattern is known at authoring time.RegExp Constructor for Dynamic Patterns: Use new RegExp(dynamicString, "i") when building regexes dynamically from user input variables. Remember to double-escape backslashes ("\d+").lastIndex on Global (/g) Regexes: Regular expressions with the /g flag maintain stateful lastIndex properties when calling .test() repeatedly.Write a regular expression /^\d{5}$/ to validate 5-digit postal codes.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.