JavaScript Regular Expressions (RegEx)

A regular expression (RegEx) is a pattern used to search, match, or manipulate text. Regular expressions are powerful tools for tasks like form validation, text searching, data parsing, and string formatting.

Real-life analogy: A regular expression is like a search template. Just as one might search a phone book with only a partial name and a pattern (e.g., "Sh*ma" to find Sharma), a regex defines a pattern to find specific text in a string.

Creating a Regular Expression

There are two ways to create a regex in JavaScript:

1. Literal Syntax (Preferred)

let pattern = /hello/;     // Matches the word "hello"
let caseInsensitive = /hello/i;  // i flag = case-insensitive

2. Constructor Syntax (When Pattern is Dynamic)

let word    = "hello";
let pattern = new RegExp(word, "i");

Regex Flags

FlagMeaning
iCase-insensitive matching
gGlobal — find all matches, not just the first
mMultiline — ^ and $ match start/end of each line
sDotall — dot (.) matches newline characters too

Testing a Pattern — test()

test() returns true if the pattern is found in the string, false otherwise.

let pattern = /javascript/i;

console.log(pattern.test("I love JavaScript!"));  // true
console.log(pattern.test("I love Python!"));       // false

// Validate phone number format
let phonePattern = /^\d{10}$/;
console.log(phonePattern.test("9876543210")); // true
console.log(phonePattern.test("98765432"));   // false

Finding Matches — match()

match() is called on a string. It returns an array of matches or null if none found.

let text  = "The price is ₹500 and the discount is ₹50.";
let nums  = text.match(/\d+/g);  // Find all number sequences

console.log(nums);  // ["500", "50"]

Searching for a Match — search()

search() returns the index of the first match, or -1 if not found.

let str = "Visit estudy247.com for tutorials";
let pos = str.search(/estudy/i);
console.log(pos);  // 6

Replacing with Regex — replace() and replaceAll()

let text = "Hello World. Hello JavaScript.";

// Replace first match
console.log(text.replace(/Hello/, "Hi"));
// Hi World. Hello JavaScript.

// Replace all matches (using g flag)
console.log(text.replace(/Hello/g, "Hi"));
// Hi World. Hi JavaScript.

Replace with a Function

let result = "apple orange banana".replace(/\b\w/g, char => char.toUpperCase());
console.log(result);  // Apple Orange Banana

Splitting with Regex — split()

let data = "Rahul; Priya,Amit  Deepa";

// Split by ; or , or multiple spaces
let names = data.split(/[;,\s]+/);
console.log(names); // ["Rahul", "Priya", "Amit", "Deepa"]

Common Regex Patterns

Character Classes

PatternMatches
\dAny digit (0–9)
\DAny non-digit
\wWord character (letter, digit, underscore)
\WNon-word character
\sWhitespace (space, tab, newline)
\SNon-whitespace
.Any character except newline

Anchors

PatternMatches
^Start of string
$End of string
\bWord boundary

Quantifiers

PatternMeaning
*Zero or more times
+One or more times
?Zero or one time (optional)
{n}Exactly n times
{n,}At least n times
{n,m}Between n and m times

Character Sets

PatternMatches
[abc]a, b, or c
[^abc]Anything except a, b, or c
[a-z]Any lowercase letter
[A-Z]Any uppercase letter
[0-9]Any digit

Groups and Capturing

Capturing Groups ( )

let date = "2026-03-08";
let match = date.match(/(\d{4})-(\d{2})-(\d{2})/);

console.log(match[0]); // 2026-03-08 (full match)
console.log(match[1]); // 2026       (year)
console.log(match[2]); // 03         (month)
console.log(match[3]); // 08         (day)

Named Capturing Groups

let pattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
let result  = "2026-03-08".match(pattern);

console.log(result.groups.year);   // 2026
console.log(result.groups.month);  // 03
console.log(result.groups.day);    // 08

Non-capturing Group (?:)

// Groups for structure only — not captured
let pattern = /(?:https?):\/\/([\w.]+)/;
let url     = "https://estudy247.com";
let match   = url.match(pattern);

console.log(match[1]); // estudy247.com

Practical Regex Patterns for Common Validations

Email Validation

function isValidEmail(email) {
  let pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return pattern.test(email);
}

console.log(isValidEmail("user@example.com")); // true
console.log(isValidEmail("invalid@"));          // false

Mobile Number (India — 10 digits starting with 6-9)

function isValidPhone(number) {
  return /^[6-9]\d{9}$/.test(number);
}

console.log(isValidPhone("9876543210")); // true
console.log(isValidPhone("1234567890")); // false

Strong Password (min 8 chars, 1 uppercase, 1 number, 1 special character)

function isStrongPassword(pwd) {
  return /^(?=.*[A-Z])(?=.*\d)(?=.*[@#$%!]).{8,}$/.test(pwd);
}

console.log(isStrongPassword("Admin@123")); // true
console.log(isStrongPassword("password"));  // false

URL Validation

function isValidURL(url) {
  return /^https?:\/\/[\w.-]+\.[a-z]{2,}(\/\S*)?$/i.test(url);
}

console.log(isValidURL("https://estudy247.com"));         // true
console.log(isValidURL("ftp://invalid"));                  // false

Remove Extra Whitespace

let messyText = "Hello    World    JavaScript";
let clean     = messyText.replace(/\s+/g, " ").trim();
console.log(clean); // Hello World JavaScript

Key Points to Remember

  • Regular expressions define patterns for searching and manipulating text
  • Use /pattern/flags literal syntax or new RegExp() for dynamic patterns
  • test() checks if a pattern exists — returns true or false
  • match() returns an array of matches; use the g flag to find all occurrences
  • replace() with a regex substitutes matched text, including all matches with the g flag
  • split() can accept a regex as the delimiter
  • Common shortcuts: \d (digit), \w (word char), \s (whitespace)
  • Use ^ and $ anchors for full-string matching (essential for validation)
  • Capturing groups () extract specific parts of a match
  • Named groups (?<name>) make extracted parts accessible by name

Leave a Comment

Your email address will not be published. Required fields are marked *