【发布时间】:2015-11-27 20:40:23
【问题描述】:
我有一个文本字段,用户必须在其中放置一个 url。我需要验证 url 格式是否有效。我需要编写一个正则表达式来查找下面的无效 url。
http://www.google.com//test/index.html //Because of double slash after host name
http:/www.google.com/test/index.html //Missing double slash for protocol
我尝试了下面的代码,它适用于第二种情况,但不适用于第一种情况
function test(url) {
var exp=/^(https?:\/\/)?((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|((\d{1,3}\.){3}\d{1,3}))(\:\d+)?(\/[-a-z\d%_.~+]*)*(\?[;&a-z\d%_.~+=-]*)?(\#[-a-z\d_]*)?$/;
return exp.test(url);
}
var firstCase="http://www.google.com//test/index.html";
alert(test(firstCase));
var secondCase = "http:/www.google.com/test/index.html";
alert(test(secondCase ));
var thirdCase="http://www.google.com/test//index.html";
alert(test(thirdCase));
【问题讨论】:
-
Its working fine for me。你能详细说明一下这里不工作的地方吗
-
试试这个工具:regex101.com 它可以让你看到哪些部分是匹配的。
-
两个斜杠通常被视为一个,另外,您应该考虑其他协议,例如mailto,ftp...
标签: javascript jquery regex