非常教程

JavaScript参考手册

RegExp

regExp.sticky

sticky 属性反映了搜索是否具有粘性( 仅从正则表达式的lastIndex属性表示的索引处搜索 )。sticky 是正则表达式对象的只读属性。

| RegExp.prototype.sticky属性的属性特性 |

|:----|

| Writable | no |

| Enumerable | no |

| Configurable | yes |

描述

sticky 的值是 Boolean ,并在“y”标志使用时为真; 否则为假。"y" 标志指示,仅从正则表达式的 lastIndex 属性表示的索引处为目标字符串匹配(并且不会尝试从后续索引匹配)。

你不能直接更改这个属性,它是只读的。

示例

使用带 sticky 标志的正则表达式

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)

锚定的 sticky 标志

火狐的 SpiderMonkey 引擎的几个版本有一个 bug,处理 ^ 断言和 sticky 标志时,会允许使用了 sticky 标志的表达式从 ^断言开始匹配,这是不应该的。这个 bug 是在 Firefox 3.6 之后的某个版本引入的(which had the sticky flag but not the bug)并于2015年修复。 可能正因为这个 bug, ES2015 规范 特别指出:

当使用带有y标识的匹配模式时,^断言总是会匹配输入的开始位置或者(如果是多行模式)每一行的开始位置。

正确行为的示例:

var regex = /^foo/y;
regex.lastIndex = 2;
regex.test('..foo');   // false - index 2 is not the beginning of the string

var regex2 = /^foo/my;
regex2.lastIndex = 2;
regex2.test('..foo');  // false - index 2 is not the beginning of the string or line
regex2.lastIndex = 2;
regex2.test('.\nfoo'); // true - index 2 is the beginning of a line

规范

Specification

Status

Comment

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'RegExp.prototype.sticky' in that specification.

Standard

Initial definition.

ECMAScript Latest Draft (ECMA-262)The definition of 'RegExp.prototype.sticky' in that specification.

Draft

浏览器兼容性

Feature

Chrome

Edge

Firefox (Gecko)

Internet Explorer

Opera

Safari

Basic support

49

13

3.0 (1.9)

No support

36

10

Prototype accessor property

?

(Yes)

38 (38)

No support

?

?

Anchored sticky(y) flag behavior per ES2015

?

(Yes)

44 (44)

No support

?

?

Feature

Android

Chrome for Android

Edge

Firefox Mobile (Gecko)

IE Mobile

Opera Mobile

Safari Mobile

Basic support

No support

49

(Yes)

1.0 (1.9)

No support

(Yes)

10

Prototype accessor property

No support

?

(Yes)

38.0 (38)

No support

?

?

Anchored sticky(y) flag behavior per ES2015

No support

?

(Yes)

44.0 (44)

No support

?

?

JavaScript

JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络