RegExp.prototype.sticky
sticky
属性反映了搜索是否具有粘性(仅从正则表达式的lastIndex
属性表示的索引处搜索)。sticky
是正则表达式对象的只读属性。
RegExp.prototype.sticky 属性的属性特性: | |
---|---|
writable | false |
enumerable | false |
configurable | true |
描述
sticky
的值是lastIndex
属性表示的索引处为目标字符串匹配(并且不会尝试从后续索引匹配)。
你不能直接更改这个属性,它是只读的。
例子
使用带 sticky 标志的正则表达式
var str = '#foo#'; var regex = /foo/y; regex.lastIndex = 1; regex.test(str); // true (译注:此例仅当 lastIndex = 1 时匹配成功,这就是 sticky 的作用) regex.lastIndex = 5; regex.test(str); // false (lastIndex 被 sticky 标志考虑到,从而导致匹配失败) regex.lastIndex; // 0 (匹配失败后重置)
锚定的 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 - 索引2不是字符串的开始 var regex2 = /^foo/my; regex2.lastIndex = 2; regex2.test("..foo"); // false - 索引2不是字符串或行的开始 regex2.lastIndex = 2; regex2.test(".\nfoo"); // true - 索引2是行的开始