0

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?

James Wilkins
  • 6,836
  • 3
  • 48
  • 73
  • 1
    Try `str.match(/^https?:\/\/(?!\/)/i);` or `str.match(/^https?:\/\/\b/i);` – Wiktor Stribiżew Mar 10 '20 at 15:40
  • Can I ask why the domain name must start with `[a-d]`? In your example you want to accept `w` which comes after `d` yet your regexp only accept `a-d` – slebetman Mar 10 '20 at 15:48
  • Does this answer your question? [Regex to test if string begins with http:// or https://](https://stackoverflow.com/questions/4643142/regex-to-test-if-string-begins-with-http-or-https) – Robert Harvey Mar 10 '20 at 15:48

3 Answers3

2

Try this one

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

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://';
James Wilkins
  • 6,836
  • 3
  • 48
  • 73
0

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.

Ezzabuzaid
  • 529
  • 1
  • 5
  • 13