Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove the global flag from a regular expression?

Given a user (developer) provided regular expression, I need to remove the global flag if it exists, on Firefox 38 and above you can just set it:

the_regex.global = false;

However that is not supported elsewhere. So, I have created this pair of functions:

function deGlobal(regex) {
  if (!regex instanceof RegExp) return regex;
  if (!regex.global) return regex;
  var parts = regExpParts(regex);
  console.log(parts);
  if (parts) {
    return new RegExp(parts.pattern, parts.flags.replace("g", ""));
  } else {
    return false;
  }
}

function regExpParts(regex) {
  if (!regex instanceof RegExp) return false;
  var regex_string = regex.toString();
  var flags = regex_string.substring(regex_string.lastIndexOf('/') + 1);
  var pattern = regex_string.substring(1, regex_string.lastIndexOf('/'));
  return {
    flags: flags,
    pattern: pattern
  };
}

Which for all of my test cases is doing great, but it seems like a very error prone method.

Is there a case where these functions wouldn't work or there a better cross browser method of doing this?

FIDDLE: http://jsfiddle.net/trex005/324k2as5/.

like image 237
trex005 Avatar asked Oct 23 '25 15:10

trex005


1 Answers

You simplify it to

new RegExp(regex.source, regex.flags);

Note RegExp.prototype.flags is introduced in ES6, so you may need to polyfill it:

if (RegExp.prototype.flags === undefined) {
  Object.defineProperty(RegExp.prototype, 'flags', {
    configurable: true,
    get: function() {
      return this.toString().match(/[gimuy]*$/)[0];
    }
  });
}
like image 139
Oriol Avatar answered Oct 25 '25 03:10

Oriol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!