Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 282
Sandy Avatar asked Apr 23 '13 11:04

Sandy


People also ask

How do I fix invalid regex?

The "Uncaught SyntaxError: Invalid regular expression: Nothing to repeat" error occurs in JavaScript when your regular expression is not valid. In order to fix the error, locate where the error is originating from, and then verify that the regular expression that you are using is valid.

What does \+ mean in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .

Does JavaScript support regex?

Using regular expressions in JavaScript. Regular expressions are used with the RegExp methods test() and exec() and with the String methods match() , replace() , search() , and split() . Executes a search for a match in a string. It returns an array of information or null on a mismatch.

What is regex in JavaScript?

A regular expression is a pattern of characters. The pattern is used to do pattern-matching "search-and-replace" functions on text. In JavaScript, a RegExp Object is a pattern with Properties and Methods.


1 Answers

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);
}
like image 132
Bergi Avatar answered Sep 28 '22 04:09

Bergi