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");

Which would produce the following output:


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

// output: gi

Which you could then split into an array:

const regex = /hello\sworld\!/gi

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

And search:

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

// output: true


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];