JavaScript RegExp g Modifier

Example

A global search for "is":

let pattern = /is/g;
let result = text.match(pattern);
Try it Yourself »

Description

The "g" modifier specifies a global match.

A global match finds all matches (not only the first).

Browser Support

/regexp/g is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Syntax

new RegExp("regexp", "g")

or simply:

/regexp/g

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, use the "i" modifier together with the g modifier.

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 modifier is set.

Example

let pattern = /W3S/g;
let result = pattern.global;
Try it Yourself »

Regular Expression Search Methods

In JavaScript, a regular expression text search, can be done with different methods.

With a pattern as a regular expression, these are the most common methods:

ExampleDescription
text.match(pattern)The String method match()
text.search(pattern)The String method search()
pattern.exec(text)The RexExp method exec()
pattern.test(text)The RegExp method test()

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.