THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript exec() 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.exec(str);

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

e
Try it yourself »

Definition and Usage

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

This method returns the matched text if it finds a match, otherwise it returns null.


Browser Support

Internet Explorer Firefox Opera Google Chrome Safari

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


Syntax

RegExpObject.exec(string)

Parameter Values

Parameter Description
string Required. The string to be searched

Return Value

Type Description
Array An array containing the matched text if it finds a match, otherwise it returns null

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.exec(str);

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

The output of the code above will be:

Hello // match for "Hello"
null // no match for "W3Schools"
Try it yourself »

RegExp Object Reference JavaScript RegExp Object