【问题标题】:Validate URL only "http://" or "https://" at the beginning of the string仅验证 URL 字符串开头的“http://”或“https://”
【发布时间】:2020-06-22 13:14:11
【问题描述】:

我正在尝试验证以“http://”或“https://”开头的字符串。一些例子:

http://example.com -> 好

http://www.example.com -> 好

https://example.com -> 好

https://www.example.com -> 好

http:///example.com -> 错误

http:/www.example.com -> 错误

https//example.com -> 错误

我有这个正则表达式,但是效果不好:

str.match(/^(http|https):\/\/?[a-d]/);

...有什么帮助吗?

【问题讨论】:

  • 试试str.match(/^https?:\/\/(?!\/)/i);str.match(/^https?:\/\/\b/i);
  • 请问为什么域名必须以[a-d]开头?在您的示例中,您想接受 w 之后的 d 但您的正则表达式只接受 a-d

标签: javascript regex url url-validation


【解决方案1】:

老实说,我不知道为什么人们想要一个正则表达式来处理每件简单的事情。如果您需要做的只是比较字符串的开头,那么在某些情况下检查它会更快,例如您所要求的(“验证开头带有单词'http://'的字符串或“https://”):

var lc = str.toLowerCase();
var isMatch = lc.substr(0, 8) == 'https://' || lc.substr(0, 7) == 'http://';

【讨论】:

    【解决方案2】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 2019-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多