Μέθοδος test() της RegExp JavaScript

Ορισμός και χρήση

test() Δοκιμή μεθόδου για την αναγνώριση συμπτώσεων στη γραμμή κειμένου.

Εάν βρεθεί σύμπτωση, επιστρέφεται true, otherwise return false.

Παράδειγμα

Παράδειγμα 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);

Try it yourself

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);

Try it yourself

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 regexp Matching text, then return true, otherwise return false.

Throws

Type Description
TypeError Throw this exception if the object called by this method is not RegExp.

Description

The RegExp object's test() Method checks if the string matches a pattern.

The test() method will check if the string string, see if it contains text matching regexp Matching text. 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 it a string s, 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
Supported Supported Supported Supported Supported Supported

Regular expression search methods

In JavaScript, regular expression text search can be completed using 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) Μέθοδος exec() της RexExp
pattern.test(text) Μέθοδος test() της RexExp