正则表达式验证URL

时间:2014-01-15 07:26:15

标签: javascript regex

我需要一个正则表达式来验证URL。
以下是有效的URL格式:

http://example.com
http://example.com/index.php
http://example.com/index.php#test
http://example.com/demo/index.php
http://example.com/demo/index.php#test
http://www.example.com
http://wwww.example.com
https://www.example.com
https://wwww.example.com

以下是无效的网址格式:

://example.com
http://example.com/index..php
http://example.com/index.php###test
http://example.com/de,mo/index.php
http://example.com/de!mo/index.php#test
http://ww.example.com
http://wwwww.example.com
htps://www.example.com
https:/wwww.example.com
http://wwww.example.com/.,.,.
http://wwww.exa_mple.com/

1 个答案:

答案 0 :(得分:0)

试试这个

var url = "http://www.example.com";
var url_regx = /^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/;

if(url.match(url_regx))
{
  alert("matched");
}
else
{
  alert("unmatched");
}

请参阅DEMO