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
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).