Good http://www.example." /> Good http://www.example." /> Good http://www.example."/>

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

7.4k views Asked by At

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?

3

There are 3 answers

0
Abey On

Try this one

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

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://';
0
Ezzabuzaid On

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

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

  1. ^(http|https): --- starts with http: or https:
  2. // --- must include double slash
  3. ([a-z]*.)? --- one optional subdomain
  4. [a-z]*. --- domain name with mandatory.
  5. [a-z]{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.