且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查输入字符串是否为有效的正则表达式?

更新时间:2023-02-26 10:50:24

您可以使用 try/catch RegExp 构造函数:

You can use try/catch and the RegExp constructor:

var isValid = true;
try {
    new RegExp("the_regex_to_test_goes_here");
} catch(e) {
    isValid = false;
}

if(!isValid) alert("Invalid regular expression");