RegExp.prototype.exec
Finds a match and returns the details: groups and position.
Available since: ES3
Syntax
regex.exec(str)Parameters
| Parameter | Type | Description |
|---|---|---|
| str | string | The string to search in. |
Return value
Array | nullAn array with the match and its groups, or null.
Examples
The match, groups and position:
const result = /(\d+)-(\d+)/.exec('Room 12-34');
console.log(result[0], result[1], result[2]);
console.log(result.index);Output:
12-34 12 34
5No match gives null:
console.log(/\d+/.exec('no digits'));Output:
nullNotes
With the g flag each call continues from lastIndex. To go through all matches matchAll() is simpler.
See also
- String.prototype.match — Finds matches of a regular expression.
- String.prototype.matchAll — Returns every match together with its groups.
- Named capture groups — Named groups — parts of a match with readable names.
In the tutorial
- Regular expressions — Regular expressions in JavaScript for beginners: patterns, flags, character classes, testing, finding and replacing text.