RegExp in JavaScript: describing a pattern to find it in text

A RegExp describes a text pattern: the two notations, test, match and replace, the flags, named groups and the lastIndex trap that comes with g.
3 min read
Believemy logo

Validating a postal code, pulling the amounts out of an invoice, replacing every date in a document: three needs that keep coming back, and that no single string method covers on its own.

A regular expression describes a pattern rather than an exact text, and the engine takes care of finding it.


Definition

A RegExp is an object describing a pattern of characters. It is written between two forward slashes, or with the constructor when the pattern is assembled at runtime.

JAVASCRIPT
const postalCode = /^\d{5}$/;

console.log(postalCode.test("75011"));   // true
console.log(postalCode.test("7501"));    // false

const typed = "believemy";
const dynamic = new RegExp("^" + typed + "$", "i");
console.log(dynamic.test("Believemy"));   // true

The literal form is the one to prefer wherever the pattern is known upfront: it reads better and avoids the double escaping forced on the String handed to the constructor.


The flags

The letters placed after the closing slash change how the engine behaves. They stack.

FlagWhat it changes
gFinds every occurrence, not the first one alone
iIgnores letter case
m^ and $ apply to each line
sThe dot also accepts line breaks
uThe pattern is read in Unicode code points


Finding, extracting, replacing

Three methods cover almost every case. test hands back a boolean, match hands back an array of results or null, replace hands back a new string.

JAVASCRIPT
const dateFr = /(?<day>\d{2})\/(?<month>\d{2})\/(?<year>\d{4})/;
const found = "shipped on 04/07/2026".match(dateFr);

console.log(found.groups.year);   // "2026"
console.log("shipped on 04/07/2026".replace(dateFr, "$<year>-$<month>-$<day>"));
// "shipped on 2026-07-04"

for (const m of "VAT 20 %, discount 15 %".matchAll(/(\d+) %/g)) {
  console.log(m[1]);   // "20" then "15"
}

Named groups, written between angle brackets right after the opening parenthesis, beat numbers by a wide margin: they read the same in the pattern and in the replacement, and adding one parenthesis no longer shifts anything.

Warning

A pattern carrying g remembers where it stopped, in its lastIndex property. Reused for a test, it therefore alternates true and false on the very same text. The rule: no g on a pattern used for testing.


Frequently asked questions

Question

Why is a regular expression sometimes very slow?

Because some patterns force the engine to try an exponential number of splits, usually when one quantifier sits inside another. On a thirty-character string, the search can then run for seconds. Simplify the pattern rather than blaming the machine.

Question

Can an email address be validated with a pattern?

Not seriously. The specification allows shapes that short patterns reject, and rejects shapes they accept. A loose check, an at sign followed later by a dot, backed by a confirmation message, validates far better than a three-line pattern.

Question

Do values coming from user input need escaping?

Always, the moment they land inside a new RegExp. A dot, a plus or a parenthesis take on their pattern meaning there and change the result, sometimes making it very costly. Run the value through an escaping function before gluing it into the pattern.

Related terms

Discover our javaScript glossary

Every word of JavaScript explained simply: keywords, built-in objects, methods, errors and concepts. Clear definitions and examples that actually run, to learn and to troubleshoot.

Share this article

Want to help us? Share this article on your networks or even better: on your site, in an article or in your newsletter.