RegExp /g Flag
Example
A global search for "is":
let text = "Is this all there is?";
let pattern = /is/g;
let result = text.match(pattern);
Try it Yourself »
Description
The /g (global) flag ensures that the regular expression finds all matches in the input string, rather than stopping after the first match.
Without the /g flag, methods like exec() will only return the first match.
Syntax
new RegExp("regexp", "g")
or simply:
/regexp/g
See Also:
The Corresponding Property: global
More Examples
Using the RegExp function exec():
let text = "Is this all there is?";
let pattern = /is/g;
let result = pattern.exec(text);
Try it Yourself »
Using the RegExp function test():
let pattern = /is/g;
let result = pattern.test(text);
Try it Yourself »
Using the String function match():
let pattern = /is/g;
let result = text.match(pattern);
Try it Yourself »
Tip
For a global, case-insensitive search, add a /i flag.
A global, case-insensitive search for "is":
Using the RegExp function exec():
let text = "Is this all there is?";
let result = /is/gi.exec(text);
Try it Yourself »
Using the RegExp function test():
let text = "Is this all there is?";
let result = /is/gi.test(text);
Try it Yourself »
Using the String function match():
let text = "Is this all there is?";
let result = text.match(/is/gi);
Try it Yourself »
Tip
You can use the global property to check if the /g flag is set.
Regular Expression Methods
Regular Expression Search and Replace can be done with different methods.
These are the most common:
String Methods
| Method | Description |
|---|---|
| match(regex) | Returns an Array of results |
| matchAll(regex) | Returns an Iterator of results |
| replace(regex) | Returns a new String |
| replaceAll(regex) | Returns a new String |
| search(regex) | Returns the index of the first match |
| split(regex) | Returns an Array of results |
RegExp Methods
| Method | Description |
|---|---|
| regex.exec() | Returns an Iterator of results |
| regex.test() | Returns true or false |
Browser Support
/regexp/g is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
| Chrome | Edge | Firefox | Safari | Opera |