Laurence Tuck
Laurence Tuck

Reputation: 420

javascript url regex

How can I allow users to enter both subdomain and domain names without the http:// prefix using a regex in javascript. I need to allow: domainname.com or www.domainname.com or www.domainname.co.uk. I have this at the moment which expects www. :

/^(?=www\.)[A-Za-z0-9_-]+\.+[A-Za-z0-9.\/%&=\?_:;-]+$/ix.test(value);

Upvotes: 0

Views: 1176

Answers (2)

Pengman
Pengman

Reputation: 708

Try this:

/^(?=www\.)?[A-Za-z0-9_-]+\.+[A-Za-z0-9.\/%&=\?_:;-]+$/

Marking the www group with a ? makes it a zero-or-one match, which is what you want as I understand it.

Tested with http://www.regular-expressions.info/javascriptexample.html

Upvotes: 1

Richard Dalton
Richard Dalton

Reputation: 35793

This seems to work when tested on http://www.regextester.com/

/^(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/

Upvotes: 0

Related Questions