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