开发者

javascript url regex

开发者 https://www.devze.com 2023-04-02 12:36 出处:网络
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 开发者_C百科or www.domainname.com or www.domainna

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 开发者_C百科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);


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


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

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

精彩评论

暂无评论...
验证码 换一张
取 消