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

Internet Explorer Firefox Opera Google Chrome Safari

The test() method is supported in all major browsers.


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