Javascript - RegExp exec() Matching

Introduction

RegExp object exec() accepts a single argument, which is the string on which to apply the pattern.

It returns an array of information about the first match or null if no match was found.

The returned array, though an instance of Array, contains two additional properties:

  • index, which is the location in the string where the pattern was matched, and
  • 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 inside the expression.

If there are no capturing groups in the pattern, then the array has only one item.

Consider the following:

Demo

var text = "this is a test test test";
var pattern = /t/gi;

var matches = pattern.exec(text);
console.log(matches.index);    //0
console.log(matches.input);    //from   ww  w  .j  av  a2  s  . c om
console.log(matches[0]);       
console.log(matches[1]);       
console.log(matches[2]);

Result

Related Topics