Modifying RegExp flags

Given the need for two identical regular expressions with different flags, instead of creating two variables:

const a = /hello\sworld\!/gi;
const b = /hello\sworld\!/g;

You could use the RegExp constructor to create a copy of the first regular expression and add new flags to it:

const x = /ab(c)/gi;
const y = new RegExp(x, "g");
console.log(y);

Which would produce the following output:

/ab(c)/g

Detecting RegExp flags

To get a string containing the flags in use on a particular regular expression, you'd use the RegExp.prototype.flags property:

const regex = /hello\sworld\!/gi
console.log(regex.flags);

// output: gi

Which you could then split into an array:

const regex = /hello\sworld\!/gi
console.log(regex.flags.split(""));

// output: ["g", "i"]

And search:

const regex = /hello\sworld\!/gi
const flags = regex.flags.split("");
console.log(flags.includes("g"));

// output: true

Polyfill

You may need to polyfill RegExp.prototype.flags as it's not supported by Internet Explorer at all.

if (RegExp.prototype.flags === undefined) {
  Object.defineProperty(RegExp.prototype, "flags", {
    configurable: true,
    get: function() {
      return this.toString().match(/[gimuy]*$/)[0];
    }
  });
}