MDN说:
使用y标志进行“粘滞”搜索,从目标字符串中当前位置开始匹配。
我不太理解它的意思。
lastIndex
属性,具体使用方式取决于g
(global)和y
(sticky)标志。 y
(sticky) 标志告诉正则表达式在lastIndex
处寻找匹配,并且仅仅在字符串中的lastIndex
位置(不是更早或更晚)进行匹配。
举个例子,胜过千言万语:
var str = "a0bc1";
// Indexes: 01234
var rexWithout = /\d/;
var rexWith = /\d/y;
// Without:
rexWithout.lastIndex = 2; // (This is a no-op, because the regex
// doesn't have either g or y.)
console.log(rexWithout.exec(str)); // ["0"], found at index 1, because without
// the g or y flag, the search is always from
// index 0
// With, unsuccessful:
rexWith.lastIndex = 2; // Says to *only* match at index 2.
console.log(rexWith.exec(str)); // => null, there's no match at index 2,
// only earlier (index 1) or later (index 4)
// With, successful:
rexWith.lastIndex = 1; // Says to *only* match at index 1.
console.log(rexWith.exec(str)); // => ["0"], there was a match at index 1.
// With, successful again:
rexWith.lastIndex = 4; // Says to *only* match at index 4.
console.log(rexWith.exec(str)); // => ["1"], there was a match at index 4.
.as-console-wrapper {
max-height: 100% !important;
}
兼容性提示:
Firefox的SpiderMonkey JavaScript引擎多年来一直有y
标志,但直到ES2015(2015年6月)才成为规范的一部分。此外,Firefox在处理y
标志与^
断言有关时长时间出现错误的情况,但在Firefox 43(存在该错误)和Firefox 47(不存在该错误)之间得到了修复。很早之前的Firefox版本(例如3.6)具有y
,没有这个错误,所以它是后来发生的回归(不定义y
标志的行为),然后被修复。