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?
Regular expression patterns are often used with modifiers (also called flags) that redefine regex behavior. Regex modifiers can be regular (e.g. /abc/i ) and inline (or embedded) (e.g. (? i)abc ). The most common modifiers are global, case-insensitive, multiline and dotall modifiers.
The RegExp m Modifier in JavaScript is used to perform multiline matching. It takes the beginning and end characters (^ and $) as working when taken over multiple lines. It matches the beginning or end of each line. It is case-sensitive.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
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") )
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).
You can write a method for it-
RegExp.prototype.reflag= function(flags){
return RegExp(this.source, flags);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With