JavaScript Regular Expressions

Learn regex patterns, flags, exec, test, match, and replace for powerful string processing.

TL;DR

  1. 01Define literal patterns with slashes or construct them using variables.
  2. 02Verify expressions with test and extract groups using matchAll.
  3. 03Replace target strings dynamically by passing matching replacement patterns.

Tips

  1. 01Use named capture groups to make complex regular expressions much easier to read and maintain.
  2. 02Create fresh regex instances or reset lastIndex to zero when executing global state matches.

Warnings

  1. 01Remember that global regular expressions maintain state between execution runs via the lastIndex property.
  2. 02Escape user-provided variables with backslashes before constructing dynamic patterns to prevent parsing failures.

Creating Patterns

    Regex literal

    Defines static patterns using forward slash brackets.

    const pattern = /hello/;
    console.log(pattern.test("hello world")); // true
    RegExp constructor

    Compiles patterns dynamically at runtime from string variables.

    const word = "hello";
    const pattern = new RegExp(word);
    console.log(pattern.test("say hello")); // true
    Character classes

    Matches specific characters from defined character sets.

    /[aeiou]/.test("hello");  // true
    /[0-9]/.test("abc123"); // true
    String anchors

    Enforces starting and ending boundaries on checks.

    /^hello/.test("hello world"); // true
    /world$/.test("hello world"); // true

Quantifiers

    Zero or more

    Matches zero or more occurrences using the asterisk operator.

    /a*b/.test("b");    // true
    /a*b/.test("aaab"); // true
    One or more

    Matches one or more occurrences using the plus operator.

    /a+b/.test("ab"); // true
    /a+b/.test("b");  // false
    Optional quantifier

    Marks elements as optional using the question mark operator.

    /colou?r/.test("color");  // true
    /colou?r/.test("colour"); // true
    Lazy matching

    Appends ? to quantifiers to match minimal characters.

    const greedy = "<a><b>".match(/<.+>/)[0];  // "<a><b>"
    const lazy = "<a><b>".match(/<.+?>/)[0]; // "<a>"

Flags and Methods

    Regex flags

    Specifies search parameters like case-insensitivity or global parsing.

    /hello/i.test("HELLO"); // true
    "hi hi".match(/hi/g); // ["hi", "hi"]
    exec() details

    Returns match arrays along with capture groups.

    const res = /(\w+)@(\w+)/.exec("user@test.com");
    // res[1] === "user", res[2] === "test"

Replacing and Testing

    String replace

    Replaces search results with new replacement string values.

    "hello world".replace(/hello/, "hi"); // "hi world"
    String replaceAll

    Replaces all matching entries globally when using g flag expressions.

    "hi hi".replaceAll(/hi/g, "hello"); // "hello hello"

Common Regex Patterns

    Validation samples

    Validates formats like phone numbers or simple emails.

    /^\d{3}-\d{3}-\d{4}$/.test("123-456-7890"); // true
    Whitespace collapse

    Collapses duplicate spaces and trims outer edges.

    const clean = " a  b ".replace(/\s+/g, " ").trim();
    // clean === "a b"

In Practice

FAQ