Ed Rooth

Personal Website + Blog + Portfolio

Mother of All Javascript URL RegExes

April 29th, 2010 by Ed

Here is a JavaScript Regular Expression that will loosely validate any URL string.

 

/^(http(s)?:\/\/)?([\w-]+\.{1})*(([\w-]*){1}(\.{1}[A-Za-z]{2,4}){1}){1}(\:{1}\d*)?([\?\/|\#]+[\@\~\;\+\'\#\,\.\%\-\/\&\?\=\w\$\s]*)*$/i

 

 

Explanation of each portion:

(http(s)?:\/\/)?
url scheme: match only "http" or "https" 0 or 1 times

 

([\w-]+\.{1})*
subdomains: match any alphanum or hyphen containing strings ending in a dot 0 or n times

 

(([\w-]*){1}(\.{1}[A-Za-z]{2,4}){1}){1}
top level domain: match exactly one [alphanum or hyphen containing string suffixed by a dot and then a 2-4 char string]

 

(:{1}\d*)?
port: match the colon and port number 0 or 1 time

 

[\@\~\;\+\'\#\,\.\%\-\/\&\?\=\w\$\s]*
query strings, anchors, filenames: allow a variety of valid characters for these



blog comments powered by Disqus
Powered by Wordpress + jQuery