-1

I need a regex to validate a URL.
Following are valid URL formats:

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

Following are invalid URL formats:

://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/
SoftProdigy
  • 153
  • 8
  • This is a frequently asked question on SO: http://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url – Dio F Jan 15 '14 at 07:36
  • I need to consider http://example.com/index..php, http://example.com/index.php###test, http://example.com/..,,. as invalid. – SoftProdigy Jan 15 '14 at 07:56
  • why is http://ww.example.com an invalid URL formal? Sure, "normally" you would expect a "www", but it is completely valid and should pass any test. Is this a homework assignment? – ygoncho Jan 15 '14 at 08:13

1 Answers1

0

try this

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");
}

See DEMO

Satish Sharma
  • 9,217
  • 6
  • 24
  • 49
  • It is not working for http://example.com/index..php, http://example.com/index.php###test, http://www.example.com/.,.,. etc. – SoftProdigy Jan 15 '14 at 07:39