beytz
beytz

Reputation:

Checking for a valid url using Javascript Regular Expressions

What is the expression I should use in order to check for a valid url in javascript?

Upvotes: 4

Views: 5665

Answers (2)

Gumbo
Gumbo

Reputation: 655707

Take a look at this complete regular expression for URLs that has been generated automatically based on the RFC 1738.

Upvotes: 7

chakrit
chakrit

Reputation: 61558

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.

Upvotes: 1

Related Questions