The flags property of the RegExp object in JavaScript returns a string containing the flags of the regular expression. This property is read-only.
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.
RegExp.flags returns value of type String
.
In JavaScript, we can retrieve the flags of a RegExp object by accessing the flags
property.
For example,
regex
with the flags 'gi'
for global and case-insensitive matching.flags
property of regex
to get the string of flags.flags
and we log it to the console.const regex = /abc/gi;
const flags = regex.flags;
console.log(flags);
gi
In JavaScript, we can compare the flags of different RegExp objects by accessing their flags
properties.
For example,
regex1
and regex2
with different sets of flags.flags
property of both objects.const regex1 = /abc/g;
const regex2 = /abc/i;
console.log(regex1.flags); // 'g'
console.log(regex2.flags); // 'i'
g i
In JavaScript, we can use the flags
property to recreate a RegExp object with the same pattern and flags.
For example,
regex1
with the pattern /abc/
and the flags 'gi'
.source
and flags
properties of regex1
.regex2
using the pattern text and flags obtained from regex1
.'ABC'
and log the result to the console.const regex1 = /abc/gi;
const pattern = regex1.source;
const flags = regex1.flags;
const regex2 = new RegExp(pattern, flags);
console.log(regex2.test('ABC'));
true
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.