← Back to Chapters

JavaScript Regular Expressions

? JavaScript Regular Expressions

⚡ Quick Overview

A Regular Expression (RegExp) is a pattern used to match character combinations in strings. In JavaScript, regex is widely used for validation, searching, and replacing text.

You can write regex using the literal form /pattern/flags or with the RegExp constructor. JavaScript then provides methods like test(), exec(), match(), and replace() to work with these patterns.

? Key Concepts

  • Pattern – what you want to find (letters, digits, words, etc.).
  • Flags – extra options like case-insensitive or global search.
  • Character classes – shortcuts like \d, \w, \s.
  • Anchors – match positions such as start (^) or end ($).
  • Quantifiers – how many times a pattern repeats (+, *, {n,m}).
  • Methods – regex and string functions that use patterns.

? Syntax and Basic Patterns

Regex syntax

? View Regex Syntax
/pattern/modifiers
// or using RegExp constructor:
new RegExp("pattern", "modifiers")

Basic patterns

? View Basic Pattern Examples
/abc/        // Matches "abc"
\d           // Matches any digit (0–9)
\w           // Matches any word character (a-z, A-Z, 0–9, _)
\s           // Matches whitespace
.            // Any single character except newline

^abc         // Must start with "abc"
abc$         // Must end with "abc"
a|b          // Matches "a" or "b"
[abc]        // Matches "a", "b", or "c"
[^abc]       // Anything except "a", "b", or "c"
[a-z]        // Range: a to z

? Modifiers (Flags)

  • i — Case-insensitive match.
  • g — Global match (find all matches, not just first).
  • m — Multi-line mode (affects ^ and $).

? Special Characters and Quantifiers

? View Special Character Shortcuts
\d     // Digits
\D     // Non-digits
\w     // Word characters
\W     // Non-word characters
\s     // Whitespace
\S     // Non-whitespace
\b     // Word boundary
\B     // Non-word boundary
.      // Any character except newline
? View Quantifier Examples
+      // One or more
*      // Zero or more
?      // Zero or one
{n}    // Exactly n
{n,}   // At least n
{n,m}  // Between n and m

? Code Examples with RegExp Methods

✅ test() – Boolean check

? View test() Example
let pattern = /hello/i;
console.log(pattern.test("Hello World"));  // true

? exec() – Detailed match

? View exec() Example
let result = /(\d+)/.exec("Price: 100 dollars");
console.log(result[0]); // "100"

? match() – Get all matches

? View match() Example
let str = "The rain in Spain";
let matches = str.match(/ain/g);
console.log(matches);  // ["ain", "ain"]

? replace() – Search and replace

? View replace() Example
let text = "Hello 123!";
let newText = text.replace(/\d+/, "***");
console.log(newText);  // "Hello ***!"

? Live Output and Explanation

? What the examples are doing

  • /hello/i.test("Hello World")true because the pattern "hello" matches regardless of case.
  • /(\d+)/.exec("Price: 100 dollars") finds the first group of digits, so result[0] is "100".
  • "The rain in Spain".match(/ain/g) → an array of all matches: ["ain", "ain"].
  • "Hello 123!".replace(/\d+/, "***") replaces the digits with "***", giving "Hello ***!".

? Common Use Cases

  • Validating emails, phone numbers, and passwords.
  • Extracting numbers or specific patterns from a string.
  • Cleaning input (removing extra spaces, unwanted characters).
  • Masking sensitive data (e.g. replacing digits in phone numbers).

? Tips & Best Practices

  • Use test() when you only need a boolean validation result.
  • Combine flags like /pattern/gi for flexible, case-insensitive global matching.
  • Use replace() with regex for powerful text substitutions.
  • Use parentheses () to group patterns and capture parts of the match.
  • Escape special characters like ., *, ? when you want them literal (e.g. /\./ for a dot).
  • Prefer clear patterns like \d or [0-9] consistently in your codebase.

? Try It Yourself

  • Write a regex that matches basic email addresses.
  • Create a regex that checks passwords with at least one number and one uppercase letter.
  • Use match() with /\d+/g to extract all numbers from a string.
  • Use replace() to mask a phone number, showing only the last two digits.
  • Experiment with \b to match whole words (e.g. match "cat" but not "scatter").