Regular expressions

ECMAScript 2026

A regular expression is a pattern for testing or finding text. Use it when you need to match several strings with the same shape, such as an order code.

On this page

Check the whole string with test()

In a literal, slashes surround the pattern. ^ and $ anchor the pattern to the start and end here. [A-Z] matches one uppercase English letter and {2} asks for two. [0-9]{3} asks for three digits.

How to try it Open a browser tab, then open Developer Tools → Console. Type the example or paste it into the Console after reviewing it, then run it. Reload before repeating declarations with the same names.

const orderCode = /^[A-Z]{2}-[0-9]{3}$/;
console.log(orderCode.test("TE-104"));
console.log(orderCode.test("TE-10"));

What to expect The checks print true and false. The second code is missing a digit.

Find multiple matches and capture groups

Use matchAll() with the g flag to visit each match. Parentheses capture a part of a match. The match array contains the full match first, followed by the captured parts. For independent test() calls, omit g and y because they can advance lastIndex on a reused expression.

How to try it Open a browser tab, then open Developer Tools → Console. Type the example or paste it into the Console after reviewing it, then run it. Reload before repeating declarations with the same names.

const line = "pen:3, notebook:2";
for (const match of line.matchAll(/([a-z]+):([0-9]+)/g)) {
  console.log(match[1], Number(match[2]));
}

What to expect The first line prints pen and 3. The second prints notebook and 2.

Official references