JavaScript regex to test, replace and extract strings

JavaScript regex matches text against patterns for validation, extraction, and replacement. Any time input follows a predictable format — dates, IDs, codes — a regular expression can test or pull out the parts that matter. Capture groups in parentheses isolate matched substrings, so a single pattern returns structured data without manual string splitting.

JavaScript Regex Example For Pattern Extraction

Output:

Output will appear here...

Output:

Has date: true
Extracted: 2024/03/15
Replaced: Order #A-123 shipped on 2024/03/15

How This Example Works

  1. /(\d{4})-(\d{2})-(\d{2})/ defines a regex literal matching an ISO-style date. \d{4} matches exactly four digits; parentheses create capture groups for year, month, and day.
  2. datePattern.test(text) returns true if the pattern matches anywhere in the string, without returning match details.
  3. text.match(datePattern) returns an array: the full match at index 0, followed by each capture group. If there’s no match, it returns null, so guard before destructuring when parsing user input.
  4. text.replace(datePattern, "$1/$2/$3") replaces the matched substring. $1, $2, and $3 insert the capture groups (year, month, day).

What Is a JavaScript Regular Expression?

A JavaScript regular expression is a RegExp object — often called a JavaScript regexp — used to match character combinations in strings. Create JavaScript regular expressions with a literal (/pattern/flags) or the RegExp constructor (new RegExp("pattern", "flags")). The engine scans left-to-right, returning the first match unless the global (g) flag is set.

Common Mistakes With JavaScript Regex

Using a global regex with test or exec.

const re = /\d+/g;
console.log(re.test("abc 123")); // true
console.log(re.test("abc 123")); // false (lastIndex advanced)
re.lastIndex = 0;
console.log(re.test("abc 123")); // true

With g or y, test/exec are stateful via lastIndex. Reset it or avoid g for boolean checks.

Forgetting double escaping in new RegExp().

new RegExp("\d+");  // pattern is "d+"
new RegExp("\\d+"); // one or more digits

In a string literal, \\ produces a single backslash, so the regex engine receives \d instead of d.

Regex Literal vs RegExp Constructor

Regex literal (/pattern/)new RegExp(pattern)
Parsed at load time; syntax errors caught earlyCompiled at runtime; errors thrown when reached
No string escaping neededRequires double backslash (\\d)
Pattern is fixed in source codePattern can be built from variables

Use a literal for static patterns. Use the constructor when the pattern includes dynamic values — but escape user input first to prevent regex injection and accidental metacharacters.

const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const re = new RegExp(escapeRegExp("a+b?"), "i");

More Examples

Replace all occurrences with replaceAll:

const masked = "card 4111-1111-1111-1111".replaceAll(/\d{4}/g, "****");
console.log(masked); // "card ****-****-****-****"

replaceAll requires the g flag when the search argument is a regex; omitting g throws a TypeError.

Extract all matches with matchAll:

const tags = [...("#js #regex #es2022".matchAll(/#(\w+)/g))];
console.log(tags.map(m => m[1])); // ["js", "regex", "es2022"]

matchAll returns an iterator of match arrays — each includes capture groups — so spreading into an array gives full access to every result.

FAQ

How do you test a regex in JavaScript?

Call regex.test(string) for a boolean result, or string.match(regex) to get match details. For multiple matches, use string.matchAll(regex) with the g flag, which returns an iterator of all match arrays including capture groups.

Does JavaScript support lookbehind assertions?

Yes. Positive lookbehind (?<=...) and negative lookbehind (?<!...) work in most modern JavaScript engines, but older browsers and some embedded runtimes may throw a syntax error.

When should you use new RegExp() instead of a literal?

Use the RegExp constructor when the pattern is not known at write time — for example, matching user-supplied search terms. For every other case, prefer a literal: it avoids double escaping, and the engine can report syntax errors at parse time rather than at runtime.