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,

  1. We create a RegExp object regex with the flags 'gi' for global and case-insensitive matching.
  2. We access the flags property of regex to get the string of flags.
  3. 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,

  1. We create two RegExp objects regex1 and regex2 with different sets of flags.
  2. We access the flags property of both objects.
  3. 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,

  1. We create a RegExp object regex1 with the pattern /abc/ and the flags 'gi'.
  2. We access the source and flags properties of regex1.
  3. We create a new RegExp object regex2 using the pattern text and flags obtained from regex1.
  4. 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.