Javascript syntax error: invalid regular expression

I am writing an application in javascript. My application has the ability to search for a string / regular expression. The problem is matching the javascript error if the user enters the wrong value. Code example:

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 line: sel/\

Returns a match js error - Uncaught SyntaxError: Invalid regular expression: /sel\/: \ at end of pattern.

Is there a way to check if the string is correct or not?

+4
source share
3 answers

Use the 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); } 
+7
source

In this case, you really do not need regular expressions, but if you want to avoid invalid characters in your expression, you should avoid this:

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

Using:

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

Without regex, you could do this:

 if (query.indexOf(filter) != -1) { } 
+11
source

Perhaps you should try to slash the string before the "var query". If you want to find a string for a slash in a regular expression, it must be escaped or regex will consider it a reserved character.

0
source

All Articles