简体   繁体   中英

Validate URL only "http://" or "https://" at the beginning of the string

I'm trying to validate a string at the beginning with the words "http://" or "https://". Some examples:

http://example.com -> Good

http://www.example.com -> Good

https://example.com -> Good

https://www.example.com -> Good

http:///example.com -> Wrong

http:/www.example.com -> Wrong

https//example.com -> Wrong

I have this regular expression, but it doesn't work well:

str.match(/^(http|https):\/\/?[a-d]/);

...any help please?

试试这个

str.match(/^(http(s)?:\/\/)[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/)

I honestly don't know why people want a regex for every simple thing. If all you need to do is compare the beginning of a string, it is much quicker to just check for it in some cases, like what you are asking for ("validate a string at the beginning with the words 'http://' or 'https://'"):

var lc = str.toLowerCase();
var isMatch = lc.substr(0, 8) == 'https://' || lc.substr(0, 7) == 'http://';

I'm not sure about the URL specification but this should work according to your request.

const URL_REGEX = /^(http|https):\/\/([az]*\.)?[az]*\.[az]{2,}(\/)?$/;

  1. ^(http|https): --- starts with http: or https:
  2. // --- must include double slash
  3. ([az]*.)? --- one optional subdomain
  4. [az]*. --- domain name with mandatory.
  5. [az]{2,} --- at least two char sub-domain suffix
  6. (/)? --- allow optional trailing slash
  7. $ --- denotes the end of the string.

Anything after the trailing slash will make the URL invalid.

https://example.com/ is valid.

https://example.com/path/to/page is invalid.

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