I'm trying to validate a string at the beginning with the words "http://" or "https://". Some examples:
-> Good
-> Good
-> Good
-> Good
http:///example -> Wrong
http:/www.example -> Wrong
https//example -> Wrong
I have this regular expression, but it doesn't work well:
str.match(/^(http|https):\/\/?[a-d]/);
...any help please?
I'm trying to validate a string at the beginning with the words "http://" or "https://". Some examples:
http://example. -> Good
http://www.example. -> Good
https://example. -> Good
https://www.example. -> Good
http:///example. -> Wrong
http:/www.example. -> Wrong
https//example. -> Wrong
I have this regular expression, but it doesn't work well:
str.match(/^(http|https):\/\/?[a-d]/);
...any help please?
Share Improve this question edited Mar 10, 2020 at 18:03 James Wilkins 7,3984 gold badges53 silver badges78 bronze badges asked Mar 10, 2020 at 15:39 user3810167user3810167 3-
1
Try
str.match(/^https?:\/\/(?!\/)/i);
orstr.match(/^https?:\/\/\b/i);
– Wiktor Stribiżew Commented Mar 10, 2020 at 15:40 -
Can I ask why the domain name must start with
[a-d]
? In your example you want to acceptw
which es afterd
yet your regexp only accepta-d
– slebetman Commented Mar 10, 2020 at 15:48 - Does this answer your question? Regex to test if string begins with http:// or https:// – Robert Harvey Commented Mar 10, 2020 at 15:48
3 Answers
Reset to default 4Try this one
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 pare 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):\/\/([a-z]*\.)?[a-z]*\.[a-z]{2,}(\/)?$/;
- ^(http|https): --- starts with http: or https:
- // --- must include double slash
- ([a-z]*.)? --- one optional subdomain
- [a-z]*. --- domain name with mandatory.
- [a-z]{2,} --- at least two char sub-domain suffix
- (/)? --- allow optional trailing slash
- $ --- denotes the end of the string.
Anything after the trailing slash will make the URL invalid.
https://example./
is valid.
https://example./path/to/page
is invalid.