RegExp.lastMatch ($&)

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.lastMatch 静态访问器属性返回最后一个匹配的子字符串。RegExp["$&"] 是该属性的别名。

¥The RegExp.lastMatch static accessor property returns the last matched substring. RegExp["$&"] is an alias for this property.

描述

¥Description

由于 lastMatchRegExp 的静态属性,因此你始终将其用作 RegExp.lastMatchRegExp["$&"],而不是用作你创建的 RegExp 对象的属性。

¥Because lastMatch is a static property of RegExp, you always use it as RegExp.lastMatch or RegExp["$&"], rather than as a property of a RegExp object you created.

每当 RegExp(但不是 RegExp 子类)实例成功匹配时,lastMatch 的值就会更新。如果没有匹配,则 lastMatch 为空字符串。lastMatch 的 set 访问器是 undefined,因此你不能直接更改此属性。

¥The value of lastMatch updates whenever a RegExp (but not a RegExp subclass) instance makes a successful match. If no matches have been made, lastMatch is an empty string. The set accessor of lastMatch is undefined, so you cannot change this property directly.

你不能将简写别名与点属性访问器 (RegExp.$&) 一起使用,因为 & 不是有效的标识符部分,因此这会导致 SyntaxError。请改用 括号表示法

¥You cannot use the shorthand alias with the dot property accessor (RegExp.$&), because & is not a valid identifier part, so this causes a SyntaxError. Use the bracket notation instead.

$& 也可以用在 String.prototype.replace() 的替换字符串中,但这与 RegExp["$&"] 旧属性无关。

¥$& can also be used in the replacement string of String.prototype.replace(), but that's unrelated to the RegExp["$&"] legacy property.

示例

¥Examples

使用 lastMatch 和$&

¥Using lastMatch and $&

js
const re = /hi/g;
re.test("hi there!");
RegExp.lastMatch; // "hi"
RegExp["$&"]; // "hi"

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看