JavaScript RegExp flags
Syntax & Examples
RegExp.flags property
The flags property of the RegExp object in JavaScript returns a string containing the flags of the regular expression. This property is read-only.
Syntax of RegExp.flags
The syntax of RegExp.flags property is:
RegExp.prototype.flags
This flags property of RegExp a string that contains the flags of the RegExp object. This property is read-only.
Return Type
RegExp.flags returns value of type String
.
✐ Examples
1 Retrieving the flags of a RegExp object
In JavaScript, we can retrieve the flags of a RegExp object by accessing the flags
property.
For example,
- We create a RegExp object
regex
with the flags'gi'
for global and case-insensitive matching. - We access the
flags
property ofregex
to get the string of flags. - The result is stored in the variable
flags
and we log it to the console.
JavaScript Program
const regex = /abc/gi;
const flags = regex.flags;
console.log(flags);
Output
gi
2 Comparing flags of different RegExp objects
In JavaScript, we can compare the flags of different RegExp objects by accessing their flags
properties.
For example,
- We create two RegExp objects
regex1
andregex2
with different sets of flags. - We access the
flags
property of both objects. - We compare the flags and log the results to the console.
JavaScript Program
const regex1 = /abc/g;
const regex2 = /abc/i;
console.log(regex1.flags); // 'g'
console.log(regex2.flags); // 'i'
Output
g i
3 Using flags property to recreate a RegExp object
In JavaScript, we can use the flags
property to recreate a RegExp object with the same pattern and flags.
For example,
- We create a RegExp object
regex1
with the pattern/abc/
and the flags'gi'
. - We access the
source
andflags
properties ofregex1
. - We create a new RegExp object
regex2
using the pattern text and flags obtained fromregex1
. - We test the new pattern on the string
'ABC'
and log the result to the console.
JavaScript Program
const regex1 = /abc/gi;
const pattern = regex1.source;
const flags = regex1.flags;
const regex2 = new RegExp(pattern, flags);
console.log(regex2.test('ABC'));
Output
true
Summary
In this JavaScript tutorial, we learned about flags property of RegExp: the syntax and few working examples with output and detailed explanation for each example.