RegExp.prototype.test
Checks whether a string matches a pattern.
Available since: ES3
Syntax
regex.test(str)Parameters
| Parameter | Type | Description |
|---|---|---|
| str | string | The string to search in. |
Return value
booleantrue if a match is found.
Examples
Does the string contain a digit:
console.log(/\d/.test('abc1'));
console.log(/\d/.test('abc'));Output:
true
falseA simple postal code format check:
const zip = /^\d{5}$/;
console.log(zip.test('10115'));
console.log(zip.test('1011'));
console.log(zip.test('10115a'));Output:
true
false
falseNotes
Without ^ and $ the pattern matches anywhere in the string. To validate the whole string always add them.
Be careful with the g flag: such a regex remembers its position in lastIndex, and calling test() again on the same string may return false.
See also
- RegExp — A regular expression — a pattern for finding and replacing text.
- String.prototype.match — Finds matches of a regular expression.
- String.prototype.includes — Checks whether a string contains a given substring.
Related recipes
In the tutorial
- Regular expressions — Regular expressions in JavaScript for beginners: patterns, flags, character classes, testing, finding and replacing text.