Bagikan melalui


exec Method

Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search.

function exec(str : String) : Array

Arguments

  • str
    Required. The String object or string literal on which to perform the search.

Remarks

If the exec method does not find a match, it returns null. If it finds a match, exec returns an array, and the properties of the global RegExp object are updated to reflect the results of the match. Element zero of the array contains the entire match, while elements 1 – n contain any submatches that have occurred within the match. This behavior is identical to the behavior of the match method without the global flag (g) set.

If the global flag is set for a regular expression, exec searches the string beginning at the position indicated by the value of lastIndex. If the global flag is not set, exec ignores the value of lastIndex and searches from the beginning of the string.

The array returned by the exec method has three properties, input, index and lastIndex. The input property contains the entire searched string. The index property contains the position of the matched substring within the complete searched string. The lastIndex property contains the position following the last character in the match.

Example

The following example illustrates the use of the exec method:

var src = "The quick brown fox jumps over the lazy dog.";

// Create regular expression pattern with a global flag.
var re = /\w+/g;

// Get the next word, starting at the position of lastindex.
var arr;
while ((arr = re.exec(src)) != null)
{
    print (arr.index + "-" + arr.lastIndex + " " + arr[0]);
}

// Output:
//  0-3 The
//  4-9 quick
//  10-15 brown
//  16-19 fox
//  20-25 jumps
//  26-30 over
//  31-34 the
//  35-39 lazy
//  40-43 dog

Requirements

Version 3

Applies To:

Regular Expression Object

See Also

Concepts

Regular Expression Syntax

Reference

match Method

RegExp Object

search Method

test Method

Change History

Date

History

Reason

July 2009

Modified the example.

Content bug fix.

March 2009

Reorganized example code and changed literal.

Information enhancement.