正则表达式.$1, …, 正则表达式.$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 the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

注意:所有全局公开最后匹配状态的 RegExp 静态属性均已弃用。请参阅 已弃用的 RegExp 功能 了解更多信息。

¥Note: All RegExp static properties that expose the last match state globally are deprecated. See deprecated RegExp features for more information.

RegExp.$1, …, RegExp.$9 静态访问器属性返回带括号的子字符串匹配项。

¥The RegExp.$1, …, RegExp.$9 static accessor properties return parenthesized substring matches.

描述

¥Description

由于 $1$9RegExp 的静态属性,因此你始终将它们用作 RegExp.$1RegExp.$2 等,而不是用作你创建的 RegExp 对象的属性。

¥Because $1$9 are static properties of RegExp, you always use them as RegExp.$1, RegExp.$2, etc., rather than as properties of a RegExp object you created.

每当 RegExp(但不是 RegExp 子类)实例成功匹配时,$1, …, $9 的值就会更新。如果未进行任何匹配,或者最后一个匹配没有相应的捕获组,则相应的属性为空字符串。每个属性的设置访问器是 undefined,因此你不能直接更改属性。

¥The values of $1, …, $9 update whenever a RegExp (but not a RegExp 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 is undefined, so you cannot change the properties directly.

带括号的子字符串的数量是无限的,但 RegExp 对象只能保存前 9 个。你可以通过返回的数组的索引访问所有带括号的子字符串。

¥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.

$1, …, $9 也可以用于 String.prototype.replace() 的替换字符串,但这与 RegExp.$n 旧属性无关。

¥$1, …, $9 can also be used in the replacement string of String.prototype.replace(), but that's unrelated to the RegExp.$n legacy properties.

示例

¥Examples

将 $n 与 RegExp.prototype.test() 一起使用

¥Using $n with RegExp.prototype.test()

以下脚本使用 RegExp.prototype.test() 方法来获取通用字符串中的数字。

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

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

请注意,任何涉及在 re.test(str) 调用和 RegExp.$n 属性之间使用其他正则表达式的操作都可能产生副作用,因此应立即访问这些特殊属性,否则结果可能会出乎意料。

¥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.

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看