JavaScript Regular Expressions: Patterns, Methods & String Validation

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.

Creating Regular Expressions

// 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");

Core RegEx Methods: test() & exec()

MethodOwnerDescription & Return Value
regex.test(str)RegExpTests for match. Returns boolean (true or false). Fast for validation!
regex.exec(str)RegExpExecutes search. Returns detailed match array with capture groups, or null.
str.match(regex)StringReturns array of matches, or null.
str.replace(regex, newStr)StringReplaces matching patterns with replacement string.

Essential Meta-Characters & Quantifiers Table

SymbolMeaningExample
^ / $Start of string / End of string anchors/^Hello$/
\d / \DAny digit [0-9] / Non-digit/\d{10}/ (10-digit phone)
\w / \WWord 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"]

University Exam Corner (BCA Examination Notes)

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

Next Step

Need a rapid cheat sheet covering all syntax, methods, and keyboard shortcuts? Proceed to the final master resource: JavaScript Quick Reference Cheat Sheet →

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!