RegExp.prototype.test()

Returns true when the regular expression finds a match anywhere in the given string.

Signature
test(str)
  • Added in JavaScript ES3 (1999)

Parameters

ParameterTypeDescription
$strstringThe string to search. Any value is coerced to a string; omitting it searches for the literal text "undefined".

Return value

booleantrue if the regular expression matches somewhere in str, otherwise false.

Changelog

  • PHP ES2015test() is defined in terms of RegExp.prototype.exec(), so a subclass that overrides exec() changes what test() reports.

test() answers one question — is there a match? — and is the cheapest regex method when you do not need the matched text. Use it for validation, guard clauses and filters; reach for exec() or String.prototype.match() only when you need the substring, its position or its capture groups.

It is stateful with g or y

A regex carrying the g or y flag remembers lastIndex, and test() advances it on every successful call. The next call resumes from there, even against a completely different string. When the search fails, lastIndex resets to 0. The visible symptom is a validator that returns true, false, true, false for four identical valid inputs.

The fix is almost never to reset lastIndex by hand — it is to drop the g flag. A validation pattern anchored with ^ and $ has no use for it.

Coercion

Non-string arguments are converted first, so /2/.test(2026) is true and /null/.test(null) is true. Check the type yourself if that would hide a bug.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Validate a hex colour, postcode or slug before saving a form
  • Filter an array of log lines down to those matching a pattern
  • Guard an expensive parse by first checking the input looks plausible

Frequently asked questions

Why does test() return false the second time on the same string?

The regex has the g or y flag, so test() left lastIndex pointing past the first match and the next call resumed from there. Remove the g flag from validation patterns, or set re.lastIndex = 0 before each call.

What is the difference between test() and match()?

test() returns a plain boolean and nothing else; String.prototype.match() returns the matched text (or an array of all matches with the g flag) or null. Use test() when you only need yes or no — it does less work and allocates no result array.

Is test() faster than includes() for a plain substring?

No. String.prototype.includes() is faster and needs no escaping for a literal substring. Use test() when the thing you are looking for is genuinely a pattern — anchors, character classes, quantifiers, alternation.

More examples

The alternating-result bug, and the fix

With g, the first call leaves lastIndex at 1, so the second starts past the end of its (one-character) string and fails, which resets lastIndex — hence the alternation. Dropping g makes every call independent.

Example · javascript
const shared = /^\d+$/g;   // g flag on a validator
console.log(["1", "2", "3", "4"].map(v => shared.test(v)));
// [ true, false, true, false ]

const fixed = /^\d+$/;     // no g flag
console.log(["1", "2", "3", "4"].map(v => fixed.test(v)));
// [ true, true, true, true ]

Arguments are coerced to strings

Every value reaches the engine as a string, so null, undefined and arrays can all match by accident. The last line shows the type guard that keeps a validator honest.

Example · javascript
console.log(/2/.test(2026));       // true  - number stringified
console.log(/null/.test(null));    // true  - "null"
console.log(/undefined/.test());   // true  - "undefined"
console.log(/1,2/.test([1, 2]));   // true  - "1,2"

const input = null;
console.log(typeof input === "string" && /^\w+$/.test(input));

Discussion

  • Be the first to comment on this lesson.