RegExp.prototype.global

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

global 访问器属性,属于 RegExp 实例,用于指示该正则表达式是否使用了 g 标志。

试一试

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;否则为 falseg 标志表示正则表达式应与字符串中所有可能的匹配项进行匹配。每次调用 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

浏览器兼容性

另见