Validating the correct URL using Javascript regular expressions

What expression should I use to validate the correct url in javascript?

+4
source share
2 answers

Take a look at this full URL regular expression that was created automatically based on RFC 1738.

+7
source

Depends on how difficult you want the check to be.

Here's the tricky trick

^(?#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|[az]{2}))(?#Port)(?::[\d]{1,5})?(?#Directories)(?:(?:(?:/(?:[-\w~!$+|.,=]|%[af\d]{2})+)+|/)+|\?|#)?(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[af\d{2}])+=(?:[-\w~!$+|.,*:=]|%[af\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[af\d{2}])+=(?:[-\w~!$+|.,*:=]|%[af\d]{2})*)*)*(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[af\d]{2})*)?$ 

In fact, regular expressions are quietly portable between platforms. Most of the Google search examples can be used in Javascript, although it is possible with a few modifications to the flavor.

+1
source

All Articles