试一试
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 |
浏览器兼容性
加载中…