Regular Expressions in JavaScript

To check whether a string follows a format, such as a code made of two letters, a hyphen and four digits, JavaScript gives you regular expressions. A regular expression, or regex, is a pattern that searches text for a particular arrangement of characters.

Here I’ll write one and make it match the whole string when you’re validating input.

What a JavaScript regular expression does

A regular expression, often called a regex, searches text for a particular arrangement of characters and is represented in JavaScript by a RegExp object.

A match answers whether the expression occurs in a string. Validation asks whether the entire value follows a rule, so boundaries are required when extra text must fail the check.

Regex syntaxMeaning
[A-Z]One uppercase letter from A through Z
\dOne digit
{4}Exactly four copies of the preceding token
^ and $Beginning and end of the input when multiline mode is off
gFind matches throughout the input, with stateful iteration

What you need to run the examples

The examples run on Node.js v26.7.0 and use built-in RegExp and String features documented by MDN, with no package dependencies.

  • A JavaScript runtime with Node.js available on your PATH.
  • Basic familiarity with strings, variables, and calling a method.

Step 1: Write a regex for the text you need

A slash-delimited regex literal finds a code made of two uppercase letters, a hyphen, and four digits anywhere in a string.

const pattern = /[A-Z]{2}-\d{4}/;
console.log(pattern.test("prefix AB-4821 suffix"));

The character class chooses one letter, while the quantifier applies to the immediately preceding class. The output is true because this expression can match a substring, even with other text around it.

Step 2: Require a whole-string match when validating

^ and $ mark the required boundaries. They make extra text before or after the expected format fail the check.

const input = "AB-4821";
const pattern = /^[A-Z]{2}-\d{4}$/;

console.log(pattern.test(input));
console.log(pattern.test("AB-4821-extra"));
Full-string validation result: valid input passes and a suffix fails.
Node.js prints true for AB-4821 and false when extra text follows.

Node.js printed true for AB-4821 and false for AB-4821-extra in the same check. That confirms the anchors reject an otherwise matching value with trailing text.

Step 3: Choose a method for the result you need

Use test() for a yes-or-no check and matchAll() when you need every result with its position or capture data. The RegExp and String APIs provide both options.

MethodUse it whenResult
test()You need a yes-or-no match checkBoolean
exec()You need the first match and capture groupsMatch array or null
match()You want match data from a stringArray or null, with behavior affected by g
matchAll()You need each global match and its capture groupsIterator of match arrays
search()You need the first matching positionIndex or -1
replace()You want to transform matching textA new string

Use test() for a pass-or-fail format check. Choose matchAll() when each result needs its position or capture data. If you need to replace every occurrence of literal text, see how to replace all occurrences of a string in JavaScript.

What the tested examples print

The test() results are true for AB-4821 and false for AB-4821-extra. The extraction example finds 12 and 34 at indexes 4 and 12 in the source string.

  • A true result confirms that the expression found a match. Whole-string validation also requires boundaries that reject unmatched text around it.
  • Use matchAll() with a global regex when the output needs each match record and its position.

Why a global test changes on the next call

A regex with the g or y flag stores its next search position in lastIndex. Each successful test() advances that position, and a failed test resets it to zero, so repeated calls can return true, true, then false for the same string.

const text = "red 12 blue 34";
const pattern = /\d+/g;

console.log(pattern.test(text), pattern.lastIndex);
console.log(pattern.test(text), pattern.lastIndex);
console.log(pattern.test(text), pattern.lastIndex);
console.log([...text.matchAll(/\d+/g)].map(match => ({ value: match[0], index: match.index }))); 
Global RegExp test calls advance lastIndex before resetting after failure.
Repeated global tests advance lastIndex, then reset it after the failed search.

The output shows lastIndex moving to 6 and then 14 before the third call fails and resets it. For a reusable yes-or-no check, leave g and y off. Keep them when iteration is the intended job.

Keep matching separate from validation

A regular expression can check a string’s shape, but that alone does not prove the value exists or can be used. For email fields, start with the browser’s email input validation or an established library, then verify ownership through the application flow when the task requires it.

When a regex is part of an input contract, keep the expression beside tests for both an accepted value and a near miss. After changing either side, rerun the check below.

console.log(/^[A-Z]{2}-\d{4}$/.test("AB-4821"));

JavaScript regular expression questions

What is a regular expression in JavaScript?

A regular expression is an expression that searches text for character arrangements. JavaScript represents it with a RegExp object that can test, extract, or replace matching text.

How do you create a regular expression in JavaScript?

Write an expression between slashes, such as /^[A-Z]{2}-\d{4}$/. Use the RegExp constructor when the expression is built at runtime, and escape backslashes inside the JavaScript string passed to it.

How do you validate a complete string with a regex?

Use ^ at the start and $ at the end of the expression, then call test(). The anchors make extra characters before or after the expected format fail the check.

Why can a global regex return different test results?

A regex with the g flag stores its next search position in lastIndex. Repeated test() calls advance that position after a match, so omit g for a reusable boolean validation check.

Aditya Gupta
Aditya Gupta

Aditya Gupta is a founding member and editor at CodeForGeek. He first found his way into tech by reading articles, and now writes approachable guides to Node.js security, authentication, AI tools, coding agents, and web scraping.

Articles: 529