Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
验证javascript/jquery中的url格式_Javascript_Jquery_Regex - Fatal编程技术网

验证javascript/jquery中的url格式

验证javascript/jquery中的url格式,javascript,jquery,regex,Javascript,Jquery,Regex,我有一个文本字段,用户必须在其中放置url。我需要验证url格式是否有效。我需要编写reg exp以查找以下无效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 我尝试了下面的代码,它适用于第二种情况,但不适用于第一种情况 fun

我有一个文本字段,用户必须在其中放置url。我需要验证url格式是否有效。我需要编写reg exp以查找以下无效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));

此正则表达式修复了您的问题,“/”后面需要一个问号,以表示零或其中一个,它以前使用*元素菜单分组,允许多个

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%.~+]*)
先前在第二组中,因此允许多次使用。你能详细说明什么不适用于此处吗?试用此工具的可能副本:它将允许你查看哪些部分是匹配的。两个斜杠通常被视为一个斜杠,此外,你还应该考虑其他协议,如mailto、ftp…警报的可能副本(测试(“));//true..此url是有效的,但表达式给出的是false。可能是这样,但这不是您的具体问题,url验证的问题远不止此