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?
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.
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 "(" .
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With