JavaScript RegExp g Modifier

Definition and usage

"g" modifier specifies global matching.

Global matching finds all matches (compared to matching only the first one).

Instance

Example 1

Global search for "is":

let pattern = /is/g;
let result = text.match(pattern);

Try it yourself

Example 2

Use regular expression function exec():

let text = "Is this all there is?";
let pattern = /is/g;
let result = pattern.exec(text);

Try it yourself

Example 3

Use regular expression function test():

let pattern = /is/g;
let result = pattern.test(text);

Try it yourself

Example 4

Use string function match():

let pattern = /is/g;
let result = text.match(pattern);

Try it yourself

Syntax

new RegExp("regexp", "g")

Or abbreviated as:

/regexp/g

Hint

For global, case-insensitive search, please use "i" modifier Used with the g modifier.

Global, case-insensitive search for "is":

Example 1

Use regular expression function exec():

let text = "Is this all there is?";
let result = /is/gi.exec(text);

Try it yourself

Example 2

Use regular expression function test():

let text = "Is this all there is?";
let result = /is/gi.test(text);

Try it yourself

Example 3

Use string function match():

let text = "Is this all there is?";
let result = text.match(/is/gi);

Try it yourself

Hint

You can use Global property Check if the g modifier is set.

let pattern = /W3S/g;
let result = pattern.global;

Try it yourself

Regular expression search methods

In JavaScript, text search using regular expressions can be completed with different methods.

UsagePattern (pattern)As regular expressions, these are the most commonly used methods:

Example Description
text.match(pattern) String method match()
text.search(pattern) String method search()
pattern.exec(text) RexExp method exec()
pattern.test(text) RexExp method test()

Browser support

/regexp/g Is ECMAScript1 (ES1) feature.

All browsers fully support ES1 (JavaScript 1997):

Chrome IE Edge Firefox Safari Opera
Support Support Support Support Support Support