RegExp.prototype.test()
Tests whether a regular expression matches a string.
Syntax
regexp.test(str)
Returns
boolean — `true` if there is a match, otherwise `false`.
Examples
console.log(/\d+/.test("abc123"));
console.log(/^\d+$/.test("abc"));
Output
true
false
const re = /a/g;
console.log(re.test("aa"), re.lastIndex);
console.log(re.test("aa"), re.lastIndex);
Output
true 1
true 2
Notes
- With the `g` or `y` flag, `test()` advances `lastIndex`, so repeated
calls walk through the string.
- Faster than `match()` when you only need a yes/no answer.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 1.0 |
| firefox | 1.0 |
| safari | 1.0 |
| edge | 12 |
| node | 0.10 |