Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

RegExp.prototype.test — checking for a match

The test() method checks whether a regular expression matches text and returns true or false. The g and y flags make matching use lastIndex, so repeated calls can produce different results.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

regexp.test(string)

Call RegExp.prototype.test as regexp.test(string). It returns true when a match is found, or false otherwise. It does not return captured groups; use exec() for those. The argument is converted to a string, and an omitted argument becomes the text "undefined".

By default, matching a substring is enough. To restrict matching to input boundaries, use the ^ and $ anchors, remembering that the m flag changes them to line boundaries.

With the standard exec(), both g and y use lastIndex to determine the starting position. With g, the search can try later positions, but y does not allow it to scan forward. In Unicode mode (with u or v), if lastIndex points to the low surrogate of a UTF-16 surrogate pair, a match can start at the preceding high surrogate, even with y. Success sets lastIndex to the end of the match; failure resets it to zero. When neither flag is set, the standard exec() still reads lastIndex and applies ToLength to its value. If that conversion succeeds, matching starts at position 0 without updating the lastIndex property. If you assign a Symbol value to lastIndex, however, test() throws a TypeError even without g or y. For independent checks, omit g and y or set lastIndex = 0 before each call.

An empty match does not automatically advance lastIndex: a loop based on test() can fail to terminate. The method uses exec(), so overriding it can change behavior. This is an ECMAScript language API, not a browser API.

Examples

const pattern = /cat/g;
console.log(pattern.test("cat"));
console.log(pattern.lastIndex);
console.log(pattern.test("cat"));
console.log(pattern.lastIndex);
pattern.lastIndex = 0;
console.log(pattern.test("cat"));

Result

true
3
false
0
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources