RegExp.exec

Executes the search for a match in a specified string. Returns a result array.

Method of RegExp

Syntax

regexp.exec( [str] )
regexp( [str] )

Parameters

Parameter Description
regexp The name of the regular expression. It can be a variable name or a literal.
str The string against which to match the regular expression. If omitted, the value of RegExp.input is used.

Description

As shown in the syntax description, a regular expression's exec method can be called either directly, (with regexp.exec(str)) or indirectly (with regexp(str)).

If you are executing a match simply to find true or false, use the RegExp.test method or the String String.search method.

If the match succeeds, the exec method returns an array and updates properties of the regular expression object and the predefined regular expression object, RegExp. If the match fails, the exec method returns null.

Consider the following example:

The following table shows the results for this script:

Object Property/Index Description Example
myArray   The contents of myArray ["dbBd", "bB", "d"]
  index The 0-based index of the match in the string 1
  input The original string cdbBdbsbz
  [0] The last matched characters dbBd
  [1], ...[n] The parenthesized substring matches, if any. The number of possible parenthesized substrings is unlimited. [1] = bB [2] = d
myRe lastIndex The index at which to start the next match. 5
  ignoreCase Indicates if the "i" flag was used to ignore case true
  global Indicates if the "g" flag was used for a global match true
  source The text of the pattern d(b+)(d)
RegExp lastMatch $& The last matched characters dbBd
  leftContext $` The substring preceding the most recent match c
  rightContext $' The substring following the most recent match bsbz
  $1, ...$9 The parenthesized substring matches, if any. The number of possible parenthesized substrings is unlimited, but RegExp can only hold the last nine. $1 = bB
$2 = d
  lastParen $+ The last parenthesized substring match, if any. d

If your regular expression uses the "g" flag, you can use the exec method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property. For example, assume you have this script:

This script produces the following results:

myArray found abb. Next match starts at 3
mySecondArry found ab. Next match starts at 9


Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.