What is the expression I should use in order to check for a valid url in javascript?
Asked
Active
Viewed 5,578 times
4
-
http://stackoverflow.com/questions/206059, 441739, 442405, 690849, 161738, etc. etc. Regex can't usefully parse URLs (see Gumbo's answer for amusing demonstration). – bobince Apr 11 '09 at 18:39
-
Also, valid on what sense? foo.com.kg is valid in the sense that it's a domain that might exist (in Krygystan), foo.com.ap isn't. There's no "ap" country code. But they're both valid in the sense that they are something.com.(two chars). – AmbroseChapel Apr 12 '09 at 05:18
2 Answers
7
Take a look at this complete regular expression for URLs that has been generated automatically based on the RFC 1738.

Gumbo
- 643,351
- 109
- 780
- 844
1
Depends no how complicated you want the check to be.
Here's an uber-complicated one:
^(?#Protocol)(?:(?:ht|f)tp(?:s?)\:\/\/|~/|/)?(?#Username:Password)(?:\w+:\w+@)?(?#Subdomains)(?:(?:[-\w]+\.)+(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))(?#Port)(?::[\d]{1,5})?(?#Directories)(?:(?:(?:/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|/)+|\?|#)?(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?$
Actually, regular expressions are quiet portable between platforms. Most examples from a google search can be used in Javascript, albeit maybe with a few "flavor" modifications.

chakrit
- 61,017
- 25
- 133
- 162