javascript syntax error: invalid regular expression

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 wrong value. Sample code:

  function myFunction() {
      var filter = $("#text_id").val();
      var query = "select * from table";
      var found;
      if (query.match(filter) != -1) {
        found = true;
      } 
      else{
        found = false;
      }
       //Do something
    }

jsfiddle: http://jsfiddle.net/ZVNMq/

Enter the string: sel/\

Match returns js error - Uncaught SyntaxError: Invalid regular expression: /sel\/: \ at end of pattern.

Is there any way to check whether the string is valid regex or not?

Answers:

Answer

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);
}
Answer

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) {
}
Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.