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.
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.
RegExp.global returns value of type Boolean
.
In JavaScript, we can check if the 'g' flag is enabled for a RegExp object by accessing the global
property.
For example,
regex
with the 'g' flag /abc/g
.global
property of regex
to see if it is true.const regex = /abc/g;
const isGlobalEnabled = regex.global;
console.log(isGlobalEnabled);
true
In JavaScript, we can compare the global
property of RegExp objects with and without the 'g' flag.
For example,
regexWithG
with the 'g' flag /abc/g
.regexWithoutG
without the 'g' flag /abc/
.global
property of both objects and log the results to the console.const regexWithG = /abc/g;
const regexWithoutG = /abc/;
console.log(regexWithG.global); // true
console.log(regexWithoutG.global); // false
true false
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,
regex
with the 'g' flag /abc/g
.global
property of regex
in an if
statement.'Global matching is enabled.'
to the console; otherwise, we log 'Global matching is not enabled.'
.const regex = /abc/g;
if (regex.global) {
console.log('Global matching is enabled.');
} else {
console.log('Global matching is not enabled.');
}
Global matching is enabled.
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.