The legacy RegExp $1, $2, $3, $4, $5, $6, $7, $8, $9 properties are static and read-only properties of regular expressions that contain parenthesized substring matches.


The $1, …, $9 properties are static, they are not a property of an individual regular expression object. Instead, you always use them as RegExp.$1, …, RegExp.$9.

The values of these properties are read-only and modified whenever successful matches are made.

The number of possible parenthesized substrings is unlimited, but the RegExp object can only hold the first nine. You can access all parenthesized substrings through the returned array's indexes.

These properties can be used in the replacement text for the String.prototype.replace() method. When used this way, do not prepend them with RegExp. The example below illustrates this. When parentheses are not included in the regular expression, the script interprets $n's literally (where n is a positive integer).


Using $n with String.prototype.replace()

The following script uses the replace() method of the String instance to match a name in the format first last and output it in the format last, first. In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.

const re = /(\w+)\s(\w+)/;
const str = "Maria Cruz";
str.replace(re, "$2, $1"); // "Cruz, Maria"
RegExp.$1; // "Maria"
RegExp.$2; // "Cruz"

Using $n with RegExp.prototype.test()

The following script uses the test() method of the RegExp instance to grab a number in a generic string.

const str = "Test 24";
const number = /(\d+)/.test(str) ? RegExp.$1 : "0";
number; // "24"

Please note that any operation involving the usage of other regular expressions between a re.test(str) call and the RegExp.$n property, might have side effects, so that accessing these special properties should be done instantly, otherwise the result might be unexpected.


Legacy RegExp features
# additional-properties-of-the-regexp-constructor

Browser compatibility

BCD tables only load in the browser

See also