RegExp.prototype.sticky

Baseline 已廣泛支援

此特性已非常成熟,可在多種裝置和瀏覽器版本上使用。自 ⁨2016 年 9 月⁩以來,它已在各大瀏覽器中可用。

sticky 訪問器屬性是 RegExp 例項的屬性,用於返回此正則表示式是否使用了 y 標誌。

試一試

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;否則為 falsey 標誌指示正則表示式僅嘗試從 lastIndex 屬性指示的索引開始匹配目標字串(與全域性正則表示式不同,它不會嘗試從任何後續索引開始匹配)。

sticky 的設定訪問器是 undefined。您不能直接更改此屬性。

對於粘滯正則表示式和 全域性 正則表示式

  • 它們從 lastIndex 開始匹配。
  • 當匹配成功時,lastIndex 會前進到匹配的末尾。
  • lastIndex 超出當前匹配字串的邊界時,lastIndex 會重置為 0。

然而,對於 exec() 方法,匹配失敗時的行為有所不同。

  • 當在粘滯正則表示式上呼叫 exec() 方法時,如果正則表示式在 lastIndex 處未能匹配,則正則表示式將立即返回 null 並將 lastIndex 重置為 0。
  • 當在全域性正則表示式上呼叫 exec() 方法時,如果正則表示式在 lastIndex 處未能匹配,它將嘗試從下一個字元開始匹配,依此類推,直到找到匹配項或到達字串末尾。

對於 exec() 方法,同時是粘滯和全域性的正則表示式的行為與粘滯但非全域性的正則表示式相同。由於 test()exec() 的簡單包裝器,因此 test() 將忽略全域性標誌並執行粘滯匹配。但是,由於許多其他方法會特殊處理全域性正則表示式的行為,因此全域性標誌通常與粘滯標誌是正交的。

示例

使用帶有粘滯標誌的正則表示式

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

瀏覽器相容性

另見