Useful Cheatsheetsusefulcheatsheets.com
JavaScript Regular Expressions
Chapter 34 · Page 268
Advanced

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.
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Regular Expressions
Chapter 34 · Page 269
Advanced

JavaScript Regular Expressions

(continued)

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
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Regular Expressions
Chapter 34 · Page 270
Advanced

JavaScript Regular Expressions

(continued)

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>"
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Regular Expressions
Chapter 34 · Page 271
Advanced

JavaScript Regular Expressions

(continued)

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"
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Regular Expressions
Chapter 34 · Page 272
Advanced

JavaScript Regular Expressions

(continued)

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"
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Regular Expressions
Chapter 34 · Page 273
Advanced

JavaScript Regular Expressions

(continued)

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"
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Regular Expressions
Chapter 34 · Page 274
Advanced

JavaScript Regular Expressions

(FAQ)

FAQ

Use the RegExp constructor when compiling patterns dynamically from variables. Use literal patterns for static definitions. Literals compile during script loading and catch syntax bugs early.

Greedy quantifiers match as many characters as possible. Lazy quantifiers append a question mark to match as few as possible. For example, .*? performs lazy matches.

Use String.prototype.matchAll() with the g flag. This returns an iterator containing complete match details and capture groups. Regular match() drops capture group indices.

The replace() method defaults to updating only the first match without a global g flag. Use replaceAll() or include the global flag to substitute all instances.

Parentheses wrap sections of patterns to create capture groups. Retrieve them using index offsets like match[1]. Alternatively, use (?<name>) syntax to query named capture groups.

Useful Cheatsheetsusefulcheatsheets.com
JavaScript Regular Expressions
Chapter 34 · Page 275
Advanced

JavaScript Regular Expressions

(In Practice)
In Practice

Parsing URL Strings with Named Groups

Parses database or web addresses using regular expression named capture groups to extract protocol and host names.

  1. 01Write a validation regular expression pattern specifying named capture groups.
  2. 02Execute the pattern against the target string address parameters.
  3. 03Confirm that a valid match details response was retrieved.
  4. 04Extract captured keys from the matched groups property index.
  5. 05Return the structured details object back to callers.
function parseConnection(str) {
  const regex =
    /^(?<proto>https?):\/\/(?<host>[^/]+)$/;

  const match = regex.exec(str);
  if (!match) return null;

  const { proto, host } = match.groups;
  return { proto, host };
}
Takeaway

Named capture groups document intent directly in patterns, making parsed string details easy to query.