JavaScript RegExp test() Method
- Previous Page exec()
- Next Page toString()
- Go to the Previous Level JavaScript RegExp Reference Manual
Definition and Usage
test()
Method to test for matches in a string.
If a match is found, return true
, otherwise return false
.
Example
Example 1
Search for the character "e" in a string:
let text = "The best things in life are free"; let pattern = /e/; let result = pattern.test(text);
Example 2
Perform a global search and test "Hello" and "W3School" in the string:
// String: let text = "Hello world!"; // Find "Hello" let pattern1 = /Hello/g; let result1 = pattern1.test(text); // Find "W3School" let pattern2 = /W3School/g; let result2 = pattern2.test(text);
Syntax
regexp.test(string)
Parameter
Parameter | Description |
---|---|
string | Required. The string to be searched. |
Return value
Type | Description |
---|---|
Boolean | If a match is found, return true, otherwise return false. |
Technical details
Return value
if the string string if the string contains text that matches regexp matching text, then return true
, otherwise return false
.
thrown
Type | Description |
---|---|
TypeError | An exception is thrown if the object called is not RegExp. |
Description
RegExp object's test()
method checks if the string matches a certain pattern.
The test() method will check if the string string, check if it contains text that matches regexp text that matches. If string if the string contains such text, this method will return true
, otherwise, return false
.
Call the test() method of the RegExp object r and pass the string s to it, which is equivalent to: (r.exec(s) != null).
Browser support
test()
It is an ECMAScript1 (ES1) feature.
All browsers fully support ES1 (JavaScript 1997):
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Supports | Supports | Supports | Supports | Supports | Supports |
Regular expression search methods
In JavaScript, regular expression text search can be completed with different methods.
UsagePattern (pattern)As regular expressions, these are the most commonly used methods:
Example | Description |
---|---|
text.match(pattern) | String method match() |
text.search(pattern) | String method search() |
pattern.exec(text) | RexExp method exec() |
pattern.test(text) | RexExp Method test() |
- Previous Page exec()
- Next Page toString()
- Go to the Previous Level JavaScript RegExp Reference Manual