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 $.
/^\d{3}-\d{4}$/.test("555-1234"); // true
/^\d{3}-\d{4}$/.test("call 555-1234"); // false
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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
gandymaketest()stateful. After a successful match,lastIndexmoves to the end of the match and the next call starts there. After a failure it resets to0. This causes alternatingtrue/falseresults when you reuse a global regex.- Leave out
gfor yes/no checks. Withoutgory,lastIndexis ignored andtest()always searches from the start. - Validation needs anchors. Without
^and$,/\d+/.test("a1b")istrue. test()does not return the match. Useexec()orString.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) makestest()check only atlastIndex, 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
ifor case-insensitive matching anduorvto treat code points correctly.
Browser support
Supported in every browser and runtime.