RegExp.exec() (Method)

This performs a non-destructive match on a target string.


ECMAScript edition - 3
JavaScript - 1.2
JScript - 3.0
Internet Explorer - 4.0
Netscape - 4.0
Netscape Enterprise Server - 3.0
Opera 5.0
Property/method value type:Array object
JavaScript syntax:-myRegExp.exec()
Argument list:aStringA string object to run a regular expression match against.

This is functionally similar to the String.match() method. It returns an enhanced array object in the same way. You would use this if you need to know the location of the matched string and whether it occurs more than once.

The g attribute is ignored for RegExp.exec() methods unlike the String.match() method.

When the exec() method is received by a global RegExp object, the lastIndex property of that RegExp object is set to point at a character location immediately following the previous match. This means you can use sub-stringing techniques to walk through the string calling exec() in an iterator until a null value is returned. This lets you build an iterator based on the pattern and the number of times it recurs in the searched string. The RegExp.exec() method does most of the work for you since it continues where it left off during the previous search. This also means you can reset the search point or commence searching wherever you like in the target string.

A short-cut mechanism to calling the exec() method is to call the RegExp itself as a function. Thus we can create a regular expression object and a target string object:

myRegExp = new RegExp("/\\d+/");

myString = "aaa 111 bbb 222 ccc";

We can execute the regular expression either like this:


Or like this:


The result of calling this method is the null value if no match occurs. Otherwise, an array as per the String.match() method is returned.

The array object has an additional property named index, which contains the character location where the match occurred. It also has an additional property called input, which contains the original string that was searched for a match.


See also:Array.index, Array.input, RegExp pattern, RegExp.$n, RegExp.input, RegExp.lastIndex, RegExp.lastMatch, RegExp.lastParen, RegExp.leftContext, RegExp.multiline, RegExp.rightContext, RegExp.test(), Regular expression, String.match(), String.replace(),, String.split()


ECMA 262 edition 3 - section -