Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท util, assert and the Test Runner

Node.js assert.match() method

Reference for assert.match() and assert.doesNotMatch() in Node.js: check a string against a regular expression and read the failure message.

assert.match(string, regexp) passes when the string matches the regular expression, and throws an AssertionError when it does not. assert.doesNotMatch() is the opposite. They are meant for output you cannot compare exactly, such as log lines with ids, generated file names or error messages with variable parts.

The failure message shows the pattern and the input, so you see at once why the match failed. Both arguments are type-checked: the first must be a string and the second must be a RegExp.

NODE
import assert from "node:assert/strict";

assert.match("order-1042", /^order-\d+$/);

Try it

Node.js Matching and not matching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Type errors and a practical check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
assert.match(string: string, regexp: RegExp, message?: string | Error): void
assert.doesNotMatch(string: string, regexp: RegExp, message?: string | Error): void
Name Description
string The text to test. It must be a string.
regexp The regular expression to match against.
message Optional text, or an Error thrown instead of the default.

Returns: undefined.

Errors: an AssertionError with operator "match" (or "doesNotMatch") when the result is wrong, including when string is not a string. A regexp that is not a RegExp throws a TypeError with code ERR_INVALID_ARG_TYPE.

Usage notes

  • The test is unanchored. /b/ matches "abc", so add ^ and $ when the whole string must have a given shape.
  • Passing a plain string as the pattern is an error. Build a RegExp and escape special characters if you need a literal match.
  • A non-string first argument fails the assertion rather than being converted, so assert.match(5, /5/) is wrong.
  • The failure message includes the input, which may be long. Trim the string first if it holds large output.
  • Be careful with the g and y flags: they make a regex stateful through lastIndex. Use a fresh regex without those flags in assertions.
  • For checking error messages directly, assert.throws() accepts a regex as well.