Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

RegExp.prototype.exec

Finds a match and returns the details: groups and position.

Available since: ES3

Syntax

regex.exec(str)

Parameters

ParameterTypeDescription
strstringThe 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
5

No match gives null:

console.log(/\d+/.exec('no digits'));

Output:

null

Notes

With the g flag each call continues from lastIndex. To go through all matches matchAll() is simpler.

See also

In the tutorial

  • Regular expressions — Regular expressions in JavaScript for beginners: patterns, flags, character classes, testing, finding and replacing text.

Thanks for reading!

Donate to the site — we work hard for you.