RegExp.prototype.test
Executes a search for a match between a regular expression and a specified string, returning true or false
Syntax
regexp.test(str)Parameters
| Parameter | Type | Description |
|---|---|---|
| str | string | The string against which to match |
Return Value
true if there is a match, false otherwise
Examples
const regex = /\d+/;
console.log(regex.test('hello 42')); // true
console.log(regex.test('hello')); // falseconst emailRegex = /^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$/;
console.log(emailRegex.test('[email protected]')); // true
console.log(emailRegex.test('invalid')); // falseconst hasUpperCase = /[A-Z]/;
const hasNumber = /\d/;
function isStrong(pw: string) {
return hasUpperCase.test(pw) && hasNumber.test(pw) && pw.length >= 8;
}
console.log(isStrong('Hello123!')); // trueUnderstanding RegExp.prototype.test
The RegExp.prototype.test method in JavaScript executes a search for a match between a regular expression and a specified string, returning true or false. It belongs to the RegExp object and is one of the most widely used methods for working with regexp values in modern JavaScript and TypeScript applications.
The method signature is regexp.test(str). It accepts 1 parameter: str. When called, it returns true if there is a match, false otherwise. Understanding when and how to use test() helps you write more expressive, readable code.
Common use cases for RegExp.prototype.test include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like regexp-exec, string-match, string-search, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for RegExp.prototype.test is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
RegExp.prototype.execExecutes a search for a match in a specified string and returns a result array or null
String.prototype.matchRetrieves the result of matching a string against a regular expression
String.prototype.searchExecutes a search for a match between a regular expression and this string, returning the index of the first match
More RegExp Methods
Other methods in the RegExp object
Related Tools
More RegExp Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.