jQuery 未终止的正则表达式文字js错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19873089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:44:49  来源:igfitidea点击:

unterminated regular expression literal js error

javascriptjqueryruby-on-railsregex

提问by Sam

I have added jQuery validator add method for the presence of http check in url field.

我已经添加了 jQuery 验证器添加方法,用于在 url 字段中检查 http 检查。

JS

JS

jQuery.validator.addMethod("valid_url", function(value, element) {
 if(!/^(https?|ftp):\/\/i.test(val))
    val = 'http://'+val; // set both the value
    $(elem).val(val); // also update the form element
 }

My Console throws
"unterminated regular expression literal"error in the following line.

我的控制台在下一行中抛出
“未终止的正则表达式文字”错误。

if(!/^(https?|ftp):\/\/i.test(val))

What my mistake is?

我的错误是什么?

采纳答案by falsetru

Regular expression literals should be surrounded by the delimiters(/). There's no terminating delimiter:

正则表达式文字应该被分隔符( /)包围。没有终止分隔符:

/^(https?|ftp):\/\//i
//                 ^


For example:

例如:

>> /^(https?|ftp):\/\//i.test('http://stackoverflow.com/')
true
>> /^(https?|ftp):\/\//i.test('telnet://stackoverflow.com/')
false

回答by Jan Kyu Peblik

You can also get this error if you're simply attempting to concatenate a variable that utilizes a regular expression and forget a quotation mark somewhere.

如果您只是尝试连接使用正则表达式的变量并忘记某处的引号,您也可能会收到此错误。