Adding modifiers to an existing regular expression

前端 未结 4 848
一生所求
一生所求 2021-01-04 01:51

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

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-04 02:36

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

提交回复
热议问题