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,}(\/)?$/;
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.