javascriptregexunicode-escapesbrowser-feature-detection

Testing for a feature of regex compilation in IE11


I would like to test for Unicode Regex Property Escapes to avoid compiling a broken regular expression in browsers that do not support it (for example IE11). Ideally, I'd like to write something along the lines of:

if (regex supports unicode property escapes) {
    return /\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F/gu;
} else {
    return /somereplacementregex/;
}

Is this possible at all? I know there are some feature detection API's but as far as I know there isn't one for regex. Alternatively if there's another way of writing this that won't break the compilation and would throw an error I can catch then that would also be great.


Solution

  • This works in Firefox or Safari; should be okay in IE11:

    let regex = /somereplacementregex/;
    try
    {
        regex = new RegExp ("\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F", "gu");
    }
    catch (e) { }
    //
    // use regex...
    console.log (regex);