javascript syntax error: invalid regular expression

前端 未结 3 501
耶瑟儿~
耶瑟儿~ 2020-12-16 01:41

I am writing an application in javascript. In my application there is an option to search for a string/regex. The problem is match returns javascript error if user types wro

3条回答
  •  独厮守ぢ
    2020-12-16 02:19

    Use a try-catch statement:

    function myFunction() {
        var filter = $("#text_id").val();
        var query = "select * from table";
        try {
            var regex = new RegExp(filter);
        } catch(e) {
            alert(e);
            return false;
        }
        var found = regex.test(query);
    }
    

提交回复
热议问题