Adding modifiers to an existing regular expression

前端 未结 4 922
一生所求
一生所求 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:30

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

提交回复
热议问题