简体   繁体   中英

Validate web url JavaScript to accept url entry google.com

I have the following regex

RegExp("((http|https)(:\/\/))?([a-zA-Z0-9]+[.]{1}){2}[a-zA-z0-9]+(\/{1}[a-zA-Z0-9]+)*\/?",
   "i");

Works fine but shows the following pattern of url as invalid

eg:"google.com"

I thank you for ur answers.

Your code requires at least something.something.something , eg stuff.google.com . Trade the {2} for a + to allow for second-level domains.

RegExp("((http|https)(://))?([a-zA-Z0-9]+[.]{1})+[a-zA-z0-9]+(/{1}[a-zA-Z0-9]+)*/?", "i");

I'll add that there are several other...oddities about this regex (like using {1} and [.] ) and that it doesn't account for some valid domains (like something-something.com ). Also, you can use regex literals in JS, like var regex = /just a regex/ . So I recommend some reading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM