RegExp's exec() does the matching.

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

The returned array contains two additional properties:

  • index, the location
  • input, the string

In the array, the first item is the string that matches the entire pattern. Any additional items represent captured groups inside the expression.

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
        var text = "room doom loom droom boom"; 
        var pattern = /om?/gi; 
        
        
        var matches = pattern.exec(text); 
        document.writeln(matches.index); //1 
        document.writeln(matches.input);
        document.writeln(matches[0]); 
        document.writeln(matches[1]); 
        document.writeln(matches[2]); 
       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo

The exec() method returns information about one match at a time. With the g flag, each call to exec() moves further into the string looking for matches:

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
        var text = "room, book, root, boom"; 
        var pattern1 = /.oo/; 
        
        
        var matches = pattern1.exec(text); 
        document.writeln(matches.index); 
        document.writeln(matches[0]); 
        document.writeln(pattern1.lastIndex); 
        
        
        matches = pattern1.exec(text); 
        document.writeln(matches.index); 
        document.writeln(matches[0]); 
        document.writeln(pattern1.lastIndex); 
       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo
 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
        var text = "room, book, root, boom"; 
        var pattern2 = /.oo/g; 
        
        var matches = pattern2.exec(text); 
        document.writeln(matches.index);//0
        document.writeln(matches[0]); //roo
        document.writeln(pattern2.lastIndex);//3
        matches = pattern2.exec(text); 
        document.writeln(matches.index);//6
        document.writeln(matches[0]); //boo
        document.writeln(pattern2.lastIndex); //9
       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo
Home 
  JavaScript Book 
    Essential Types  

REGEXP:
  1. The Regexp Type
  2. RegExp constructor
  3. RegExp Instance Properties
  4. RegExp's exec() does the matching.
  5. RegExp's test()
  6. RegExp's toLocaleString() and toString()
  7. RegExp Constructor Properties