THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML

JavaScript test() Method

RegExp Object Reference JavaScript RegExp Object

Example

Search a string for the character "e":

var str = "The best things in life are free";
var patt = new RegExp("e");
var res = patt.test(str);

Since there is an "e" in the string, the result of res will be:

true
Try it Yourself »

Definition and Usage

The test() method tests for a match in a string.

This method returns true if it finds a match, otherwise it returns false.


Browser Support

Method
test() Yes Yes Yes Yes Yes

Syntax

RegExpObject.test(string)

Parameter Values

Parameter Description
string Required. The string to be searched

Return Value

Type Description
Boolean Returns true if it finds a match, otherwise it returns false

Technical Details

JavaScript Version: 1.2

More Examples

Example

Do a global search, and test for "Hello" and "W3Schools" in a string:

// The string:
var str = "Hello world!";

// Look for "Hello"
var patt = /Hello/g;
var result = patt.test(str);

// Look for "W3Schools"
patt2 = /W3Schools/g;
result2 = patt2.test(str);

The output of the code above will be:

true // match for "Hello"
false // no match for "W3Schools"
Try it Yourself »

RegExp Object Reference JavaScript RegExp Object