Design & Download
Your JS Library
in Seconds!!!

Snippet: flagRegExp() - Modify RegExp Flags

Written by Christopher West (cwest) on November 16, 2015.
Creates a new version of a regular expression in which the flags are modified.
function flagRegExp(rgx, modifiers) {
  var flags = (rgx + '').replace(/[\s\S]+\//, '');
  modifiers.replace(/([-+!]?)(\w)/g, function(index, op, flag) {
    index = flags.indexOf(flag)
    flags = op == '-' || (op == '!' && index >= 0)
      ? flags.replace(flag, '')
      : index < 0
        ? flags + flag
        : flags;
  return new RegExp(rgx.source, flags);

At times its necessary to create a new version of a given RegExp but with different flags. For example we may need to make sure that a RegExp has the g (global) flag. Now with the YourJS.flagRegExp() we can easily get this done:

var rgxTrim = /^\s+|\s$/;
var rgxTrimGlobal = YourJS.flagRegExp(rgxTrim, '+g');

var str = '   Hello world!   ';
console.log(JSON.stringify(str.replace(rgxTrim, ''));
// -> "Hello world!   "
console.log(JSON.stringify(str.replace(rgxTrimGlobal, ''));
// -> "Hello world!"

flagRegExp(...) API Documentation


Creates a new copy of a regular expression with modified flags.


  1. rgx {RegExp}:
    The RegExp to be duplicated with modified flags.
  2. modifiers {string}:
    Specifies how to modify the flags of the duplicate of rgx. The standard flags are of course g for global, i for ignoreCase and m for multiline. In some environments other flags are also available. In order to assure that the duplicate will have specified flag you can just add the flag character (optionally you can prefix it with a +) to the string. In order to assure that the duplicate will exclude a specified flag you can enter - followed by the flag character in this string. In order to toggle the flag in the duplicate you can prefix the flag character with !. For example `"g-i!m"` (which is the same as `"+g-i!m"`) will ensure the `g` flag is included, ensure the `i` flag is excluded and toggle `m`.


Returns a duplicate of rgx with modified flags as specified by the modifiers string.