Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
147
rated 0 times [  154] [ 7]  / answers: 1 / hits: 64054  / 11 Years ago, tue, april 23, 2013, 12:00:00

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?


More From » regex

 Answers
31

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

[#78688] Monday, April 22, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
antoinette

Total Points: 206
Total Questions: 99
Total Answers: 95

Location: Guam
Member since Tue, Nov 29, 2022
2 Years ago
;