RegExp.$1, …, RegExp.$9
Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see thecompatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
Note:AllRegExp static properties that expose the last match state globally are deprecated. Seedeprecated RegExp features for more information.
TheRegExp.$1, …, RegExp.$9 static accessor properties return parenthesized substring matches.
In this article
Description
Because$1–$9 are static properties ofRegExp, you always use them asRegExp.$1,RegExp.$2, etc., rather than as properties of aRegExp object you created.
The values of$1, …, $9 update whenever aRegExp (but not aRegExp subclass) instance makes a successful match. If no matches have been made, or if the last match does not have the corresponding capturing group, the respective property is an empty string. The set accessor of each property isundefined, so you cannot change the properties directly.
The number of possible parenthesized substrings is unlimited, but theRegExp object can only hold the first nine. You can access all parenthesized substrings through the returned array's indexes.
$1, …, $9 can also be used in the replacement string ofString.prototype.replace(), but that's unrelated to theRegExp.$n legacy properties.
Examples
>Using $n with RegExp.prototype.test()
The following script uses theRegExp.prototype.test() method 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 are.test(str) call and theRegExp.$n property, might have side effects, so that accessing these special properties should be done instantly, otherwise the result might be unexpected.
Specifications
| Specification |
|---|
| Legacy RegExp features> # additional-properties-of-the-regexp-constructor> |