18

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?

2
  • 1
    try catch is the fastest and painless way. Commented Apr 23, 2013 at 11:44
  • heeding nhahtdh's advice would be a good idea in any case. in your specific situation you have to escape the escape symbol ``. generally speaking you should escape all characters having a special meaning in a regexp if you allow unvalidated user input of the pattern. if you just happen to store the data in dom nodes you'll probably get along without the extra effort. Commented Apr 23, 2013 at 11:51

4 Answers 4

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) {
}
Sign up to request clarification or add additional context in comments.

1 Comment

I didn't need the regex in my case. Simple search. Thanks for pointing that out!
15

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

Comments

1
    RegExp.quote = function allowSpecialSymbols(str) {
      return str.replace(/([.?*+^$[\]\\(){}|-])/g, '');
    };
    const regExp = new RegExp(RegExp.quote('some \ string'), 'i');

Also, you can escape special characters.

1 Comment

This answer doesn't seem to be much different from this already provided answer.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.