Julian TF Julian TF - 1 year ago 53
Javascript Question

Is it possible to modify flags on an existing RegExp?

My code receives a RegExp object (out of my control). It isn't global but I need it to be.

At the moment I'm doing this:

if (!regex.global) {
var flags = 'g';
if (regex.ignoreCase) flags += 'i';
if (regex.multiline ) flags += 'm';
if (regex.sticky ) flags += 'y';
regex = new RegExp(regex.source, flags);

...because I can't figure out any other way.

  • regex.global
    doesn't have a setter.

  • regex.compile(new_pattern)
    is deprecated in favour of
    new RegExp(new_pattern)

  • regex.flags
    isn't a thing

Is there a better way to do this?

Answer Source

I'm afraid the answer is "No".

There is no way to change the flags on a existing regex. What you're doing seems to be the cleanest way.

You (arguably) could shorten the optional flags a bit:

var flags = 'g' +
    (regex.ignoreCase ? 'i' : '') +
    (regex.multiline ? 'm' : '') +
    (regex.sticky ? 'y' : '');