Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท RegExp

RegExp.prototype.test()

Reference for JavaScript RegExp test(): check whether a string matches a pattern, avoid the lastIndex trap with the g flag, and validate input.

The test() method of a regular expression checks whether a string contains a match and returns true or false. It is the simplest and fastest way to ask "does this text fit the pattern?" when you do not need the matched text itself.

By default a pattern can match anywhere in the string, so /cat/.test("concatenate") is true. To require the whole string to fit, anchor the pattern with ^ and $.

JavaScript
/^\d{3}-\d{4}$/.test("555-1234"); // true
/^\d{3}-\d{4}$/.test("call 555-1234"); // false

Try it

JS Searching and validating

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

No output.

JS The lastIndex trap

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

No output.

Syntax

JavaScript
regex.test(string)
Name Description
string The text to search. Other values are converted to a string first, so undefined becomes "undefined".

Return value: true if there is at least one match, otherwise false.

Exceptions: none for ordinary input. A TypeError is thrown if you call test() on something that is not a regular expression.

Usage notes

  • g and y make test() stateful. After a successful match, lastIndex moves to the end of the match and the next call starts there. After a failure it resets to 0. This causes alternating true/false results when you reuse a global regex.
  • Leave out g for yes/no checks. Without g or y, lastIndex is ignored and test() always searches from the start.
  • Validation needs anchors. Without ^ and $, /\d+/.test("a1b") is true.
  • test() does not return the match. Use exec() or String.prototype.match() when you need captured text.
  • Faster than match() for simple yes/no checks, because it does not build a result array.
  • Sticky (y) makes test() check only at lastIndex, which is useful for tokenizers.
  • Real-world validation: regexes can reject obviously bad input, but cannot prove an email address works. Keep patterns simple and verify on the server.
  • Case and Unicode: add i for case-insensitive matching and u or v to treat code points correctly.

Browser support

Supported in every browser and runtime.