Free beginner tutorial

JavaScript Regular Expressions

A regular expression, or regex, describes a text pattern. JavaScript can use a pattern to check a string, find matching text, or extract parts of it.

Create a pattern

Write a regular expression between slashes. In this example, \d represents a digit and {4} means four repetitions.

const yearPattern = /^\d{4}$/;

console.log(yearPattern.test("2026")); // true
console.log(yearPattern.test("26"));   // false

The ^ and $ anchors require the pattern to match the whole string. Without them, test() can return true when a match appears anywhere inside the input.

Use character classes and flags

Character classes let one part of a pattern match a range or category of characters. Flags change how a pattern searches: for example, i ignores letter case and g finds matches across a string.

const colorPattern = /#([0-9a-f]{6})/i;
const result = "Brand color: #F48024".match(colorPattern);

console.log(result[1]); // "F48024"

The parentheses create a capture group. The complete match is at index 0; the captured six-character value is at index 1.

Use named groups to extract values

A named capture makes the returned result easier to read when a pattern has more than one group.

const datePattern = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/;
const match = "2026-11-26".match(datePattern);

if (match) {
  console.log(match.groups.year);  // "2026"
  console.log(match.groups.month); // "11"
}

Choose between test(), match() and replace()

Use test() when you only need a true or false result. Use match() to get matching text and capture groups. Use replace() when a matched part should be changed.

const spaces = /\s+/g;
const cleanText = "JavaScript   patterns".replace(spaces, " ");

console.log(cleanText); // "JavaScript patterns"

Use regex for focused checks

Regular expressions are useful for simple formats such as a four-digit year or a short code. They are not a replacement for complete parsers or server-side validation. For example, a quick email pattern cannot check every valid email address.

A regular expression with the g or y flag is stateful when reused with test(). For a simple repeated yes/no check, use a pattern without those flags or reset its lastIndex.

Practice a small text task

Try extracting a product code from a sentence, then use replace() to collapse repeated spaces. For related input handling, see JavaScript strings and form validation.