JavaScript RegExp test() Method
- Previous Page
- Next Page
- Go to the Previous Level JavaScript RegExp Reference Manual
Definition and Usage
test()
Method tests for matches in the test string.
If a match is found, it returns true
, otherwise return false
.
Instance
Example 1
Search for the character "e" in the 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 contains text that matches regexp matching text, then return true
, otherwise return false
.
Throw
Type | Description |
---|---|
TypeError | Throw this exception if the object called is not RegExp. |
Description
RegExp object's test()
Method checks if a string matches a certain pattern.
The test() method will check if the string string, see if it contains text that matches regexp text that matches. If string contains such text, the 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()
Is ECMAScript1 (ES1) feature.
All browsers fully support ES1 (JavaScript 1997):
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Support | Support | Support | Support | Support | Support |
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
- Next Page
- Go to the Previous Level JavaScript RegExp Reference Manual