RegExp exec() Methods

Description

RegExp exec() accepts the target string, and returns an array of information about the first match or null if no match was found.

The returned array is an instance of Array with two additional properties:

  • index, which is the location in the string where the pattern was matched
  • input, which is the string that the expression was run against

The first item in the array is the string that matches the entire pattern.

Any additional items represent captured groups. In case of no capturing groups, the array has only one item.

Example


var text = "this is a test";
var pattern = /is/gi;
//w  w w  .j  a  va 2 s .  co m
var matches = pattern.exec(text);
console.log(matches.index);
console.log(matches.input);
console.log(matches[0]);
console.log(matches[1]);
console.log(matches[2]);

The code above generates the following result.

Note

exec() returns one match at a time even for global pattern.

Without the global flag, calling exec() on the same string multiple times returns information about the first match.

With the g flag, each call to exec() moves to the next matches.


var text = "cat, bat, sat, fat, hat, gate,ate.appropriate";
var pattern1 = /.at/;
//www .j av a 2 s .co m
var matches = pattern1.exec(text);
console.log(matches.index);        
console.log(matches[0]);           
console.log(pattern1.lastIndex);   

matches = pattern1.exec(text);
console.log(matches.index);        
console.log(matches[0]);           
console.log(pattern1.lastIndex);   

var pattern2 = /.at/g;
var matches = pattern2.exec(text);

console.log(matches.index);        
console.log(matches[0]);           
console.log(pattern2.lastIndex);   

matches = pattern2.exec(text);
console.log(matches.index);        
console.log(matches[0]);           
console.log(pattern2.lastIndex);   

matches = pattern2.exec(text);
console.log(matches.index);        
console.log(matches[0]);           
console.log(pattern2.lastIndex);   

matches = pattern2.exec(text);
console.log(matches.index);        
console.log(matches[0]);           
console.log(pattern2.lastIndex);   

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions