test method
The test method checks if a
string contains at least one match
with regular expression.
If there is - true is returned,
and if not - false.
Syntax
string.test(regular expression);
Example
Let's check if there is a time in a string:
let str = '12:39';
let reg = /\d\d:\d\d/;
let res = reg.test(str);
console.log(res);
The code execution result:
true
Example
Let's check if an entire string matches a regular expression:
let str = '12:39';
let reg = /^\d\d:\d\d$/;
let res = reg.test(str);
console.log(res);
The code execution result:
true
Example
Let's check if the string contains only digits:
let str = '123';
let reg = /^\d+$/;
let res = reg.test(str);
console.log(res);
The code execution result:
true
See also
-
the
matchmethod
that searches for matches in a string -
the
matchAllmethod
that searches for all matches in a string -
the
execmethod
that performs a sequential search -
the
replacemethod
that performs search and replacement -
the
searchmethod
that performs a search -
the
splitmethod
that splits a string