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 valu
Solution 1:
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) {
}
Solution 2:
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);
}
Solution 3:
RegExp.quote = function allowSpecialSymbols(str) {
return str.replace(/([.?*+^$[\]\\(){}|-])/g, '');
};
const regExp = new RegExp(RegExp.quote('some \ string'), 'i');
Also, you can escape special characters.
Solution 4:
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.
Post a Comment for "Javascript Syntax Error: Invalid Regular Expression"