简体   繁体   中英

Javascript regular expression check flag support

In javascript, how can i check if a certain flag in regular expression is supported or not ?
For some new flags, i keep getting "invalid regular expression flag" error.

You can use RegExp constructor. It prevents syntax error and allows you to optionally detect and use that flag without aborting execution.

function isRegExpFlagSupported() {
    try {
        var regexp = new RegExp("foo.*bar", "s");
        return true;
    } catch (ex) {
        return false;
    }
}

If you execute it outside try-catch block like this,

var regexp = new RegExp("foo.*bar", "s");

it will throw error "invalid regular expression flag s".

If you don't know the composition of the regex then can convert it into a string and use a regex to capture the letters after the last / character. Like /test/gi.toString().match(/\\w*$/); // <- ["gi"] /test/gi.toString().match(/\\w*$/); // <- ["gi"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM