Adding modifiers to an existing regular expression

Jinu Joseph Daniel picture Jinu Joseph Daniel · Feb 24, 2012 · Viewed 7.3k times · Source

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?

Answer

epascarello picture epascarello · Feb 24, 2012

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