Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

Issue with regex for website validation in JavaScript

I am currently using the following regex to validate a website:

^((https?)://)?([w|W]{3}.)[a-zA-Z0-9-.]{3,}.[a-zA-Z]{2,}(.[a-zA-Z]{2,})?$

This is currently working for:

http://www.google.com
www.google.com

but not for

google.com
http://google.com

Please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to make thr group matching www. optional

^((https?)://)?([wW]{3}.)?[a-zA-Z0-9-.]{3,}.[a-zA-Z]{2,}(.[a-zA-Z]{2,})?$
                            ^

See demo

I am just pointing how to adjust your regex to match the strings you specified. Actually, the topic has been thoroughly covered on SO. For example, please check Trying to Validate URL Using JavaScript post to see how URL can be validated in JavaScript.

Also, a bit of searching over the Web can show some other solutions, like in URL Validation using Regular Expression in Javascript:

^(?:(?:https?|ftp)://)?(?:S+(?::S*)?@)?(?:(?!10(?:.d{1,3}){3})(?!127(?:.d{1,3}){3})(?!169.254(?:.d{1,3}){2})(?!192.168(?:.d{1,3}){2})(?!172.(?:1[6-9]|2d|3[0-1])(?:.d{1,3}){2})(?:[1-9]d?|1dd|2[01]d|22[0-3])(?:.(?:1?d{1,2}|2[0-4]d|25[0-5])){2}(?:.(?:[1-9]d?|1dd|2[0-4]d|25[0-4]))|(?:(?:[a-zu00a1-uffff0-9]+-?)*[a-zu00a1-uffff0-9]+)(?:.(?:[a-zu00a1-uffff0-9]+-?)*[a-zu00a1-uffff0-9]+)*(?:.(?:[a-zu00a1-uffff]{2,})))(?::d{2,5})?(?:/[^s]*)?$

It is a bit adjusted, see how it works here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...