JavaScript RegExp global
Syntax & Examples

RegExp.global property

The global property of the RegExp object in JavaScript indicates whether the 'g' flag, which tests the regular expression against all possible matches in a string, is set. This property is read-only.


Syntax of RegExp.global

The syntax of RegExp.global property is:

RegExp.prototype.global

This global property of RegExp whether to test the regular expression against all possible matches in a string, or only against the first. This property is read-only.

Return Type

RegExp.global returns value of type Boolean.



✐ Examples

1 Checking if the global property is enabled

In JavaScript, we can check if the 'g' flag is enabled for a RegExp object by accessing the global property.

For example,

  1. We create a RegExp object regex with the 'g' flag /abc/g.
  2. We check the global property of regex to see if it is true.
  3. We log the result to the console.

JavaScript Program

const regex = /abc/g;
const isGlobalEnabled = regex.global;
console.log(isGlobalEnabled);

Output

true

2 Comparing global property with and without the 'g' flag

In JavaScript, we can compare the global property of RegExp objects with and without the 'g' flag.

For example,

  1. We create a RegExp object regexWithG with the 'g' flag /abc/g.
  2. We create another RegExp object regexWithoutG without the 'g' flag /abc/.
  3. We check the global property of both objects and log the results to the console.

JavaScript Program

const regexWithG = /abc/g;
const regexWithoutG = /abc/;
console.log(regexWithG.global); // true
console.log(regexWithoutG.global); // false

Output

true
false

3 Using global property in conditional statements

In JavaScript, we can use the global property in conditional statements to perform different actions based on whether the 'g' flag is enabled.

For example,

  1. We create a RegExp object regex with the 'g' flag /abc/g.
  2. We check the global property of regex in an if statement.
  3. If the property is true, we log 'Global matching is enabled.' to the console; otherwise, we log 'Global matching is not enabled.'.

JavaScript Program

const regex = /abc/g;
if (regex.global) {
  console.log('Global matching is enabled.');
} else {
  console.log('Global matching is not enabled.');
}

Output

Global matching is enabled.

Summary

In this JavaScript tutorial, we learned about global property of RegExp: the syntax and few working examples with output and detailed explanation for each example.