Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

我们的志愿者还没有将这篇文章翻译为 中文 (简体)加入我们帮助完成翻译!

The sticky property reflects whether or not the search is sticky (searches in strings only from the index indicated by the lastIndex property of this regular expression). sticky is a read-only property of an individual regular expression object.

Property attributes of RegExp.prototype.sticky
Writable no
Enumerable no
Configurable yes

Description

The value of sticky is a Boolean and true if the "y" flag was used; otherwise, false. The "y" flag indicates that it matches only from the index indicated by the lastIndex property of this regular expression in the target string (and does not attempt to match from any later indexes).

You cannot change this property directly. It is read-only.

Examples

Using a regular expression with the sticky flag

var str = '#foo#';
var regex = /foo/y;

regex.lastIndex = 1;
regex.test(str); // true
regex.lastIndex = 5;
regex.test(str); // false (lastIndex is taken into account with sticky flag)
regex.lastIndex; // 0 (reset after match failure)

Anchored sticky flag

This behavior was specified in ES2015 and differs from a previous Firefox implementation: "When the y flag is used with a pattern, ^ always matches only at the beginning of the input, or (if multiline is true) at the beginning of a line".

var regex = /^foo/y;
regex.lastIndex = 2; // disallows to match at the beginning of the string
regex.test("..foo"); // false

var regex2 = /^foo/my;
regex2.lastIndex = 2;
regex2.test("..foo"); // false
regex2.lastIndex = 2;
regex2.test(".\nfoo"); // true

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'RegExp.prototype.sticky' in that specification.
Standard Initial definition.
ECMAScript 2017 Draft (ECMA-262)
The definition of 'RegExp.prototype.sticky' in that specification.
Draft  

Browser compatibility

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support No support (Yes) 3.0 (1.9) No support No support No support
Prototype accessor property No support (Yes) 38 (38) No support No support No support
Anchored sticky(y) flag behavior per ES2015 No support (Yes) 44 (44) No support No support No support
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support No support No support 1.0 (1.9) No support No support No support
Prototype accessor property No support No support 38.0 (38) No support No support No support
Anchored sticky(y) flag behavior per ES2015 No support No support 44.0 (44) No support No support No support

See also

文档标签和贡献者

 此页面的贡献者: m_gol, ustccjw, yisibl, fscholz, x2357, Mingun, ziyunfei, stevemao, kscarfone, Sheppy, ostorj
 最后编辑者: m_gol,