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

javascriptstring.test(regular expression);

Example

Let's check if there is a time in a string:

javascriptlet str = '12:39';
let reg = /\d\d:\d\d/;

let res = reg.test(str);
console.log(res);

The code execution result:

javascripttrue

Example

Let's check if an entire string matches a regular expression:

javascriptlet str = '12:39';
let reg = /^\d\d:\d\d$/;

let res = reg.test(str);
console.log(res);

The code execution result:

javascripttrue

Example

Let's check if the string contains only digits:

javascriptlet str = '123';
let reg = /^\d+$/;

let res = reg.test(str);
console.log(res);

The code execution result:

javascripttrue

See also

  • the match method
    that searches for matches in a string
  • the matchAll method
    that searches for all matches in a string
  • the exec method
    that performs a sequential search
  • the replace method
    that performs search and replacement
  • the search method
    that performs a search
  • the split method
    that splits a string