问题
I have a bunch of regular expressions like lower = /[a-z]/ Later in my program i need to use this as /[a-z]/g ie. i need to add the 'global' modifier later. So how to add a modifier to an existing regular expression?
回答1:
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") )
回答2:
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).
回答3:
You can write a method for it-
RegExp.prototype.reflag= function(flags){
return RegExp(this.source, flags);
}
回答4:
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.
来源:https://stackoverflow.com/questions/9437203/adding-modifiers-to-an-existing-regular-expression