JavaScript Pattern Matching with RegExp Examples

Learn JavaScript pattern matching with regular expressions using search(), match(), matchAll(), replace(), split(), and the RegExp constructor.

Published

Updated

Read time 4 min read

Reviewed byDeepak Prasad

JavaScript Pattern Matching with RegExp Examples

JavaScript pattern matching usually means searching text with regular expressions. A regular expression, or RegExp, describes a text pattern that JavaScript can search, extract, replace, or split. This is useful for validating input, finding IDs in logs, extracting dates, replacing sensitive digits, and working with structured strings.

This article shows the main JavaScript pattern matching methods and when to use each one: search(), match(), matchAll(), replace(), split(), and RegExp.

Environment: Node.js v20.18.2. After each runnable snippet, the following paragraph states the expected console output (order and values).


Use search() when you only need the position where a pattern first appears. It returns the first matching index or -1 if no match is found.

javascript
const text = "Order 104 ships on 2026-06-11";

console.log("search-index:", text.search(/\d{3}/));
Output

You should see one line logging search-index: 6.

The pattern /\d{3}/ finds the first group of three digits, so the match starts at index 6.


Method 2: Extract a Match with match()

Use match() when you want the matching text. Without the global g flag, the result includes details about the first match. With g, it returns all matched strings.

javascript
const text = "Order 104 ships on 2026-06-11";

console.log("match:", text.match(/\d{4}-\d{2}-\d{2}/)[0]);
Output

You should see one line logging match: 2026-06-11.

This pattern extracts a date formatted as YYYY-MM-DD.


Method 3: Replace Matched Text with replace()

Use replace() when pattern matching should transform the string.

javascript
const text = "Order 104 ships on 2026-06-11";

console.log("replace:", text.replace(/\d/g, "#"));
Output

You should see one line logging replace: Order ### ships on ####-##-##.

The global g flag replaces every digit. Without g, only the first matching digit would be replaced.


Method 4: Get Every Match with matchAll()

Use matchAll() when you need every match along with match details such as capture groups and indexes. The regular expression must include the global g flag.

javascript
const text = "Order 104 ships on 2026-06-11";
const numbers = [...text.matchAll(/\d+/g)].map((match) => match[0]);

console.log("matchAll:", numbers.join("|"));
Output

You should see one line logging matchAll: 104|2026|06|11.

matchAll() returns an iterator, so spreading it into an array is a common pattern before mapping or filtering results.


Method 5: Split a String with a Pattern

Use split() with a regular expression when separators vary.

javascript
const line = "alpha, beta;gamma  delta";
const parts = line.split(/[;,\s]+/);

console.log(parts);
Output

You should see one line logging [ 'alpha', 'beta', 'gamma', 'delta' ].

The pattern matches commas, semicolons, or whitespace, so one expression handles multiple separators.


Method 6: Build a RegExp Dynamically

Use the RegExp constructor when part of the pattern comes from a variable.

javascript
const word = "error";
const pattern = new RegExp("\\b" + word + "\\b", "i");

console.log(pattern.test("Server Error found"));
Output

You should see one line logging true.

When user input becomes part of a dynamic regular expression, escape special regex characters first. Otherwise, characters such as ., *, and [ can change the meaning of the pattern.


Common Questions About JavaScript Pattern Matching

Does JavaScript have pattern matching like switch expressions?

JavaScript has regular expression pattern matching for strings. It does not have a built-in general-purpose pattern matching expression like some functional languages, although proposals and libraries may use that term differently.

Which method should I use for JavaScript regex matching?

Use test() for a true/false check, search() for the first index, match() for matched text, matchAll() for all matches with details, and replace() when the result should be a changed string.

Why is my regex only matching once?

Most JavaScript regex methods need the global g flag to process every occurrence. For example, /\d/ matches one digit in replace(), while /\d/g replaces every digit.


Summary

JavaScript pattern matching is mainly handled with regular expressions and string methods. Use search() to find the first position, match() to extract matching text, matchAll() to collect every match, replace() to transform strings, and split() to divide strings by flexible separators. For dynamic patterns, use RegExp carefully and escape user input before building the expression.


Official Documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …