How to check if the input string is a valid Regular expression?

前端 未结 5 696
北荒
北荒 2020-12-08 13:07

How do you check, in JavaScript, if a string is a proper regular expression that will compile?

For example, when you execute the following javascript, it produces a

5条回答
  •  情话喂你
    2020-12-08 13:42

    You can use try/catch and the RegExp constructor:

    var isValid = true;
    try {
        new RegExp("the_regex_to_test_goes_here");
    } catch(e) {
        isValid = false;
    }
    
    if(!isValid) alert("Invalid regular expression");
    

提交回复
热议问题