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.globalThis 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,
- We create a RegExp object
regexwith the 'g' flag/abc/g. - We check the
globalproperty ofregexto see if it is true. - 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,
- We create a RegExp object
regexWithGwith the 'g' flag/abc/g. - We create another RegExp object
regexWithoutGwithout the 'g' flag/abc/. - We check the
globalproperty 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); // falseOutput
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,
- We create a RegExp object
regexwith the 'g' flag/abc/g. - We check the
globalproperty ofregexin anifstatement. - 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.