我有一个文本字段,用户必须放置一个网址。我需要验证url格式是否有效。我需要编写一个reg-exp来查找下面的无效网址。
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));
答案 0 :(得分:0)
此正则表达式修复了您的问题," /"在它之后需要一个问号,以表示零或其中一个,它之前被分组了一个*元素menaing mulitple被允许
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);
}
alert(test("http://www.google.com//bla")); //false
alert(test("http:/www.google.com/test/index.html")); //false
alert(test("http://www.google.com/bla")); //true
更具体一点:这里第一组(\/?)([-a-z\d%_.~+]*)
中的斜线早于第二组,因此被允许多次