javascript syntax error: invalid regular expression

前端 未结 3 489
耶瑟儿~
耶瑟儿~ 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);
    }
    
    0 讨论(0)
  • 2020-12-16 02:20

    Perhaps you should try escaping the slashes on a line before the "var query". If you want to search a string for a slash in regex, it must be escaped or regex will read it as a reserved character.

    0 讨论(0)
  • 2020-12-16 02:29

    In this case you didn't actually need regular expressions, but if you want to avoid invalid characters in your expression you should escape it:

    RegExp.quote = function(str) {
         return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    };
    

    Usage:

    var re = new RegExp(RegExp.quote(filter));
    

    Without a regular expression you could have done this:

    if (query.indexOf(filter) != -1) {
    }
    
    0 讨论(0)
提交回复
热议问题