javascript语法错误:正则表达式无效 [英] javascript syntax error: invalid regular expression
本文介绍了javascript语法错误:正则表达式无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用JavaScript编写应用程序.在我的应用程序中,有一个搜索字符串/正则表达式的选项.问题是,如果用户键入错误的值,则匹配项将返回javascript错误.示例代码:
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/
jsfiddle: http://jsfiddle.net/ZVNMq/
输入字符串: sel/\
匹配返回js错误-未捕获的SyntaxError:模式结尾处无效的正则表达式:/sel \/:\.
有什么方法可以检查字符串是否为有效的正则表达式?
Is there any way to check whether the string is valid regex or not?
推荐答案
使用try-catch语句:
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);
}
这篇关于javascript语法错误:正则表达式无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文