試一試
const str = "table football";
const regex = /foo/y;
regex.lastIndex = 6;
console.log(regex.sticky);
// Expected output: true
console.log(regex.test(str));
// Expected output: true
console.log(regex.test(str));
// Expected output: false
描述
如果使用了 y 標誌,則 RegExp.prototype.sticky 的值為 true;否則為 false。y 標誌指示正則表示式僅嘗試從 lastIndex 屬性指示的索引開始匹配目標字串(與全域性正則表示式不同,它不會嘗試從任何後續索引開始匹配)。
sticky 的設定訪問器是 undefined。您不能直接更改此屬性。
對於粘滯正則表示式和 全域性 正則表示式
- 它們從
lastIndex開始匹配。 - 當匹配成功時,
lastIndex會前進到匹配的末尾。 - 當
lastIndex超出當前匹配字串的邊界時,lastIndex會重置為 0。
然而,對於 exec() 方法,匹配失敗時的行為有所不同。
- 當在粘滯正則表示式上呼叫
exec()方法時,如果正則表示式在lastIndex處未能匹配,則正則表示式將立即返回null並將lastIndex重置為 0。 - 當在全域性正則表示式上呼叫
exec()方法時,如果正則表示式在lastIndex處未能匹配,它將嘗試從下一個字元開始匹配,依此類推,直到找到匹配項或到達字串末尾。
對於 exec() 方法,同時是粘滯和全域性的正則表示式的行為與粘滯但非全域性的正則表示式相同。由於 test() 是 exec() 的簡單包裝器,因此 test() 將忽略全域性標誌並執行粘滯匹配。但是,由於許多其他方法會特殊處理全域性正則表示式的行為,因此全域性標誌通常與粘滯標誌是正交的。
String.prototype.matchAll()(呼叫RegExp.prototype[Symbol.matchAll]()):y、g和gy均不同。- 對於
y正則表示式:matchAll()會丟擲錯誤;[Symbol.matchAll]()會恰好一次地生成exec()的結果,而不會更新正則表示式的lastIndex。 - 對於
g或gy正則表示式:返回一個迭代器,該迭代器生成一系列exec()的結果。
- 對於
String.prototype.match()(呼叫RegExp.prototype[Symbol.match]()):y、g和gy均不同。- 對於
y正則表示式:返回exec()的結果並更新正則表示式的lastIndex。 - 對於
g或gy正則表示式:返回一個包含所有exec()結果的陣列。
- 對於
String.prototype.search()(呼叫RegExp.prototype[Symbol.search]()):g標誌始終無關緊要。- 對於
y或gy正則表示式:如果字串的開頭匹配,則始終返回0;如果字串的開頭不匹配,則返回-1,並且在退出時不會更新正則表示式的lastIndex。 - 對於
g正則表示式:返回字串中第一個匹配項的索引,如果沒有找到匹配項,則返回-1。
- 對於
String.prototype.split()(呼叫RegExp.prototype[Symbol.split]()):y、g和gy行為相同。String.prototype.replace()(呼叫RegExp.prototype[Symbol.replace]()):y、g和gy均不同。- 對於
y正則表示式:在當前的lastIndex處替換一次,並更新lastIndex。 - 對於
g和gy正則表示式:替換exec()匹配到的所有出現。
- 對於
String.prototype.replaceAll()(呼叫RegExp.prototype[Symbol.replace]()):y、g和gy均不同。- 對於
y正則表示式:replaceAll()會丟擲錯誤。 - 對於
g和gy正則表示式:替換exec()匹配到的所有出現。
- 對於
示例
使用帶有粘滯標誌的正則表示式
js
const str = "#foo#";
const 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)
錨定粘滯標誌
在多個版本中,Firefox 的 SpiderMonkey 引擎在 ^ 斷言和粘滯標誌方面存在 一個 bug,該 bug 允許以 ^ 斷言開頭並使用粘滯標誌的表示式在不應匹配時進行匹配。此 bug 在 Firefox 3.6(具有粘滯標誌但無 bug)之後一段時間引入,並於 2015 年修復。也許是由於這個 bug,規範 專門指出:
即使在使用
y標誌的模式中,^也始終只匹配輸入的開頭,或者(如果 rer.[[Multiline]] 為true)匹配行的開頭。
正確行為示例
js
const regex1 = /^foo/y;
regex1.lastIndex = 2;
regex1.test("..foo"); // false - index 2 is not the beginning of the string
const 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
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-get-regexp.prototype.sticky |
瀏覽器相容性
載入中…