最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Validate URL only "http:" or "https:" at the beginning of the string - Stack Ov

programmeradmin2浏览0评论

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); or str.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 accept w which es after d yet your regexp only accept a-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
Add a ment  | 

3 Answers 3

Reset to default 4

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

  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./ is valid.

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

发布评论

评论列表(0)

  1. 暂无评论