RegExp

RegExp.prototype.exec

Executes a search for a match in a specified string and returns a result array or null

Syntax

JavaScript
regexp.exec(str)

Parameters

ParameterTypeDescription
strstringThe string against which to match

Return Value

An array with the matched text and captured groups, or null

Examples

Basic Usage
const regex = /(\d{4})-(\d{2})-(\d{2})/;
const result = regex.exec('Date: 2024-01-15');
if (result) {
  console.log(result[1]); // '2024'
  console.log(result[2]); // '01'
}
Practical Example
const regex = /\b(\w+)\b/g;
const str = 'hello world';
let match;
while ((match = regex.exec(str)) !== null) {
  console.log(match[1], 'at', match.index);
}
Advanced Usage
const regex = /(?<year>\d{4})-(?<month>\d{2})/;
const result = regex.exec('2024-06');
console.log(result?.groups?.year); // '2024'
console.log(result?.groups?.month); // '06'

Understanding RegExp.prototype.exec

The RegExp.prototype.exec method in JavaScript executes a search for a match in a specified string and returns a result array or null. It belongs to the RegExp object and is one of the most widely used methods for working with regexp values in modern JavaScript and TypeScript applications.

The method signature is regexp.exec(str). It accepts 1 parameter: str. When called, it returns an array with the matched text and captured groups, or null. Understanding when and how to use exec() helps you write more expressive, readable code.

Common use cases for RegExp.prototype.exec include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like regexp-test, string-match, string-matchall, enabling you to chain operations together for complex data manipulation pipelines.

Browser support for RegExp.prototype.exec is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.

Browser Compatibility

Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.

Related Methods

More RegExp Methods

Other methods in the RegExp object

Related Tools

More RegExp Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.