Reputation: 6291
I have a bunch of regular expression, e.g. /[a-z]/
. Later in my program I need to have this as /[a-z]/g
,
so I need to add the 'global' modifier later. How can I add a modifier to an existing regular expression?
Upvotes: 22
Views: 11116
Reputation: 207501
Use RegEx source and flags to separate the regular expression from the flags. Then create a new one with the string and set the needed flags.
var re = /^[a-z]*$/;
var re2 = new RegExp(re.source, re.flags + "i");
console.log( re.test("abc") )
console.log( re.test("ABC") )
console.log( re2.test("abc") )
console.log( re2.test("ABC") )
Upvotes: 30
Reputation: 1357
One aspect not really covered in earlier answers, so adding my two cents...
The excellent answers (+1 for epascarello!) here don't quite cover all the bases. If you want to generalize the function to allow any flags added to any regex:
function addregexflags(regx, newflags) {
// add new flags without duplication (won't work in old browsers or IE)
newflags = [...new Set([...regx.flags.split(''), ...newflags.split('')])].join('');
return new RegExp(regx.source, newflags);
}
addregexflags(/try/gi, "gm"); // /try/gim
If you have to support older browsers that don't support Sets and the spread operator, you need to longhand the union of strings as the RegExp constructor does not allow replication of flags.
Upvotes: 1
Reputation: 104760
You can write a method for it-
RegExp.prototype.reflag= function(flags){
return RegExp(this.source, flags);
}
Upvotes: 5
Reputation: 370
Here is a function to build on epascarello's answer and the comments. You said you have quite a few of regexps to modify later on, you could just redefine the variable they are referenced in or make some new ones with a function call.
function modifyRegexpFlags(old, mod) {
var newSrc = old.source;
mod = mod || "";
if (!mod) {
mod += (old.global) ? "g" : "";
mod += (old.ignoreCase) ? "i" : "";
mod += (old.multiline) ? "m" : "";
}
return new RegExp(newSrc, mod);
}
var lower = /[a-z]/;
//Some code in-between
lower = modifyRegexpFlags(lower, "g");
If the second argument is omitted, the old modifiers will be used.
(Credit to davin for the idea).
Upvotes: 4