試一試
const regex1 = /foo/g;
console.log(regex1.global);
// Expected output: true
const regex2 = /bar/i;
console.log(regex2.global);
// Expected output: false
描述
如果使用了 g 標誌,RegExp.prototype.global 的值為 true;否則為 false。g 標誌表示正則表示式應與字串中所有可能的匹配項進行匹配。每次呼叫 exec() 都會更新其 lastIndex 屬性,以便下一次呼叫 exec() 時從下一個字元開始搜尋。
某些方法,例如 String.prototype.matchAll() 和 String.prototype.replaceAll(),會驗證如果引數是正則表示式,則該正則表示式必須是全域性的。正則表示式的 [Symbol.match]() 和 [Symbol.replace]() 方法(由 String.prototype.match() 和 String.prototype.replace() 呼叫)在正則表示式是全域性的時也會有不同的行為。
global 的設定器是 undefined。您不能直接修改此屬性。
示例
使用 global
js
const globalRegex = /foo/g;
const str = "fooexamplefoo";
console.log(str.replace(globalRegex, "")); // example
const nonGlobalRegex = /foo/;
console.log(str.replace(nonGlobalRegex, "")); // examplefoo
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-get-regexp.prototype.global |
瀏覽器相容性
載入中…