A Regular Expression (RegEx) is a specialized sequence of characters defining a search pattern. In JavaScript, regular expressions are full first-class objects (RegExp) used for pattern matching, string searching, text parsing, and form data validation.
// 1. Regular Expression Literal (Preferred)
const emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/i;
// 2. RegExp Constructor (Used when pattern is dynamic)
const userInput = "javascript";
const dynamicPattern = new RegExp(userInput, "gi");
test() & exec()| Method | Owner | Description & Return Value |
|---|---|---|
regex.test(str) | RegExp | Tests for match. Returns boolean (true or false). Fast for validation! |
regex.exec(str) | RegExp | Executes search. Returns detailed match array with capture groups, or null. |
str.match(regex) | String | Returns array of matches, or null. |
str.replace(regex, newStr) | String | Replaces matching patterns with replacement string. |
| Symbol | Meaning | Example |
|---|---|---|
^ / $ | Start of string / End of string anchors | /^Hello$/ |
\d / \D | Any digit [0-9] / Non-digit | /\d{10}/ (10-digit phone) |
\w / \W | Word character [a-zA-Z0-9_] / Non-word | /\w+/ |
+ / * / ? | 1 or more / 0 or more / 0 or 1 (Optional) | /https?/ (Matches http or https) |
{min, max} | Range quantifier | /\d{4,6}/ |
[abc] | Character set (matches a, b, or c) | /[aeiou]/ (Vowels) |
// Practical Example: Extracting Indian 10-digit Phone Numbers
const text = "Contact our support at 9876543210 or alternate office desk 8765432109.";
const phoneRegex = /[6-9]\d{9}/g;
const matches = text.match(phoneRegex);
console.log("Discovered Phone Numbers:", matches); // ["9876543210", "8765432109"]
Exam Question: "Write a JavaScript regular expression to validate a strong password (at least 8 characters, 1 uppercase, 1 lowercase, 1 number, and 1 special symbol)."
const strongPasswordPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
console.log(strongPasswordPattern.test("VeewomPass@2026")); // true
console.log(strongPasswordPattern.test("weakpass")); // false
Need a rapid cheat sheet covering all syntax, methods, and keyboard shortcuts? Proceed to the final master resource: JavaScript Quick Reference Cheat Sheet →